package com.greyu.ysj.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpException;
import org.apache.poi.hssf.record.PageBreakRecord.Break;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.zxing.Result;
import com.greyu.ysj.authorization.annotation.Authorization;
import com.greyu.ysj.authorization.annotation.DuplicateSubmitToken;
import com.greyu.ysj.authorization.manager.TokenManager;
import com.greyu.ysj.authorization.model.TokenModel;
import com.greyu.ysj.config.Constants;
import com.greyu.ysj.config.ResultStatus;
import com.greyu.ysj.entity.Admin;
import com.greyu.ysj.entity.CbtArea;
import com.greyu.ysj.entity.CbtAsset;
import com.greyu.ysj.entity.CbtAutoExchange;
import com.greyu.ysj.entity.CbtBallot;
import com.greyu.ysj.entity.CbtChange;
import com.greyu.ysj.entity.CbtChangeDraw;
import com.greyu.ysj.entity.CbtCoininfo;
import com.greyu.ysj.entity.CbtConstant;
import com.greyu.ysj.entity.CbtCreateCoin;
import com.greyu.ysj.entity.CbtDraw;
import com.greyu.ysj.entity.CbtExchange;
import com.greyu.ysj.entity.CbtFeedback;
import com.greyu.ysj.entity.CbtIncome;
import com.greyu.ysj.entity.CbtInvest;
import com.greyu.ysj.entity.CbtInvitedIncome;
import com.greyu.ysj.entity.CbtMinerRate;
import com.greyu.ysj.entity.CbtNews;
import com.greyu.ysj.entity.CbtPayLog;
import com.greyu.ysj.entity.CbtRatio;
import com.greyu.ysj.entity.CbtRecharge;
import com.greyu.ysj.entity.CbtReward;
import com.greyu.ysj.entity.CbtTransfer;
import com.greyu.ysj.entity.CbtUserStar;
import com.greyu.ysj.entity.CbtUserUpdate;
import com.greyu.ysj.entity.CbtVote;
import com.greyu.ysj.entity.CbtVoteRecharge;
import com.greyu.ysj.entity.InvTree;
import com.greyu.ysj.entity.Node;
import com.greyu.ysj.entity.User;
import com.greyu.ysj.mapper.CbtAssetMapper;
import com.greyu.ysj.model.ResultModel;
import com.greyu.ysj.service.AdminService;
import com.greyu.ysj.service.CbtAreaService;
import com.greyu.ysj.service.CbtAssetService;
import com.greyu.ysj.service.CbtAutoExchangeService;
import com.greyu.ysj.service.CbtBallotService;
import com.greyu.ysj.service.CbtChangeDrawService;
import com.greyu.ysj.service.CbtChangeService;
import com.greyu.ysj.service.CbtCoinInfoService;
import com.greyu.ysj.service.CbtConstantService;
import com.greyu.ysj.service.CbtCreateCoinService;
import com.greyu.ysj.service.CbtDrawService;
import com.greyu.ysj.service.CbtExchangeService;
import com.greyu.ysj.service.CbtFeedBackService;
import com.greyu.ysj.service.CbtIncomeService;
import com.greyu.ysj.service.CbtInvestService;
import com.greyu.ysj.service.CbtInvitedIncomeService;
import com.greyu.ysj.service.CbtMinerRateService;
import com.greyu.ysj.service.CbtMinerRatioService;
import com.greyu.ysj.service.CbtNewsService;
import com.greyu.ysj.service.CbtPayLogService;
import com.greyu.ysj.service.CbtRatioService;
import com.greyu.ysj.service.CbtRechargeService;
import com.greyu.ysj.service.CbtRewardService;
import com.greyu.ysj.service.CbtTransferService;
import com.greyu.ysj.service.CbtUserStarService;
import com.greyu.ysj.service.CbtUserUpdateMapperService;
import com.greyu.ysj.service.CbtVoteRechargeService;
import com.greyu.ysj.service.CbtVoteService;
import com.greyu.ysj.service.InvTreeService;
import com.greyu.ysj.service.InvitationTreeService;
import com.greyu.ysj.service.UserService;
import com.greyu.ysj.service.impl.InvitationTreeServiceImpl;
import com.greyu.ysj.utils.CoinQuotations;
import com.greyu.ysj.utils.FileDownload;
import com.greyu.ysj.utils.FileTemplateUtils;
import com.greyu.ysj.utils.FileUtil;
import com.greyu.ysj.utils.International;
import com.greyu.ysj.utils.InvestFlag;
import com.greyu.ysj.utils.NodeItem;
import com.greyu.ysj.utils.SendMail;
import com.greyu.ysj.utils.SendPhoneMessage;
import com.greyu.ysj.utils.SubZero;
import com.greyu.ysj.utils.WalletAccount;
import com.greyu.ysj.utils.WalletProcess;





@RestController
@RequestMapping("/cbt")
public class CbtController {
	@Autowired
	private UserService userService;
	@Autowired
	private TokenManager tokenManager;
	@Autowired
	private CbtAssetService cbtAssetService;
	@Autowired
	private CbtInvestService cbtInvestService;
	@Autowired
	private CbtIncomeService cbtIncomeService;
	@Autowired
	private CbtNewsService cbtNewsService;
	@Autowired
	private CbtCoinInfoService cbtCoinInfoService;
	@Autowired
	private CbtDrawService cbtDrawService;
	@Autowired
	private CbtVoteService cbtVoteService;
	@Autowired
	private CbtBallotService cbtBallotService;
	@Autowired
	private CbtVoteRechargeService cbtVoteRechargeService;
	@Autowired
	private CbtRechargeService cbtRechargeService;
	@Autowired
	private CbtTransferService cbtTransferService;
	@Autowired
	private CbtPayLogService cbtPayLogService;
	@Autowired
	private CbtRatioService cbtRatioService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private AdminService adminService;
	@Autowired
	private CbtCreateCoinService cbtCreateCoinService;
	@Autowired
	private CbtConstantService cbtConstantService;
	@Autowired
	private CbtRewardService cbtRewardService;
	@Autowired
	private CbtFeedBackService cbtFeedBackService;
	@Autowired
	private CbtInvitedIncomeService cbtInvitedIncomeService;
	@Autowired
	private CbtChangeService cbtChangeService;
	@Autowired
	private CbtMinerRateService cbtMinerRateService;
	@Autowired
	private CbtMinerRatioService cbtMinerRatioService;
	
	@Autowired
	private CbtExchangeService cbtExchangeService;
	
	@Autowired
	private InvitationTreeService invitationTreeService;
	@Autowired
	private CbtUserUpdateMapperService cbtUserUpdateMapperService;
	@Autowired
	private InvTreeService invTreeService;
	@Autowired
	private CbtAssetMapper cbtAssetMapper;
	
	@Autowired
	private CbtAreaService cbtAreaService;
	
	@Autowired
	private CbtChangeDrawService cbtChangeDrawService;
	@Autowired
	private CbtAutoExchangeService cbtAutoExchangeService;
	@Autowired
	private CbtUserStarService cbtUserStarService;
	@Autowired
	private TokenManager manager;
	
	private int getUserIdbyToken(){
		String authorization = request.getHeader(Constants.AUTHORIZATION);
        TokenModel model = this.manager.getToken(authorization);
        if (null !=model) {
			return model.getUserId();
		}
		return -1;
	}
	/**
	 * 检查安卓版本更新
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkUpdate", method = RequestMethod.GET)
	public ResponseEntity<ResultModel> checkUpdate() throws IOException {
		String path = Constants.FILE_PATH + "/version.json";
		//String path ="F:/001/version.json";
		return FileDownload.checkUpdate(path);

	}
	
	/**
	 * 检查苹果版本更新
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/checkIOSUpdate", method = RequestMethod.GET)
	public ResponseEntity<ResultModel> checkIOSUpdate() throws IOException {
		String path = Constants.IOS_FILE_PATH + "/version_ios.json";
		//String path ="F:/001/version_ios.json";
		return FileDownload.checkUpdate(path);
	}
	
	@RequestMapping(value = "/testfunction", method = RequestMethod.POST)
	public ResponseEntity<ResultModel> testfunction(@RequestParam("userId") Integer userId) {
		int referer=this.userService.selectLeaderIdByuserId(userId);
		
		return new ResponseEntity<>(ResultModel.ok(referer), HttpStatus.OK);
	}

	/**
	 * 文件下载
	 */
	@GetMapping(value = "/filedownload")
	public void filedownload(HttpServletRequest request, HttpServletResponse response) {
		FileTemplateUtils.downloanFromExcelTemplate("update.json", "file", request, response);
	}

	/**
	 * 用户通过手机号登陆
	 * 
	 */
	@PostMapping(value = "/loginByPhone")
	public ResponseEntity<ResultModel> loginByPhone(@RequestParam("phone") String phone,
			@RequestParam("passWord") String passWord,@RequestParam("area") String area) {
		System.out.println(phone);
		System.out.println(passWord);
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//校验用户输入的手机号
		
		if (Integer.valueOf(area)==86) {
			if(!phone.matches(Constants.REGEX_MOBILE)){
				return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"phoneError"), HttpStatus.OK);
			}
		}else{
			if(!phone.matches(Constants.REGEX_MOBILEs)){
				return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"phoneError"), HttpStatus.OK);
			}
		}
//		if(!phone.matches(Constants.REGEX_MOBILE)){
//			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"phoneError"), HttpStatus.OK);
//		}
		if (null == phone || null == passWord) {
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"dataCannotBeNull"), HttpStatus.OK);
		}

		User user = this.userService.selectByPhoneAndCode(phone,area);

		if (null == user || // 未注册
				!user.getPassWord().equals(passWord)) { // 密码错误
			// 提示用户名或者密码错误
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNameOrPassWordError"), HttpStatus.OK);
		}
		// 生成token，保存用户登录状态
		TokenModel model = this.tokenManager.createToken(user.getUserId());
		//去除敏感信息
        user.setPassWord("");
		user.setMailNum("");
		user.setUserName("");
        user.setPayPassword("");
        user.setIdcardUrla("");
        user.setIdcardUrlb("");
        user.setWalletBtcPrivatekey("");
        user.setWalletEthPrivatekey("");
		String UserJson = JSON.toJSONString(user);
		JSONObject userObject = JSON.parseObject(UserJson);
		//初始化用户资产
		int userId=user.getUserId();
		double asset = this.cbtAssetService.getAsset(userId);
		//验证用户是否已签到
		CbtReward signIn=this.cbtRewardService.selectRewardByuserId(userId);
		if (signIn==null) {
			userObject.put("signInFlag", 0);
		}else {
			userObject.put("signInFlag", 1);
		}
		CbtArea selectAreaByUserId = cbtAreaService.selectAreaByUserId(userId);
		userObject.put("area",selectAreaByUserId.getAccount());
		userObject.put("asset", asset);
		userObject.put("token", model.getToken());
		
		return new ResponseEntity<>(ResultModel.ok(userObject), HttpStatus.OK);
	}
	
	
	/**
	 * 用户通过邮箱登陆
	 * 
	 */
	@PostMapping(value = "/loginByEmail")
	public ResponseEntity<ResultModel> loginByEmail(@RequestParam("email") String email,
			@RequestParam("passWord") String passWord) {
		System.out.println(email);
		System.out.println(passWord);
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//校验用户输入的邮箱
		if(!email.matches(Constants.REGEX_EMAIL)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"emailError"), HttpStatus.OK);
		}
		if (null == email || null == passWord) {
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"dataCannotBeNull"), HttpStatus.OK);
		}

		User user = this.userService.selectByEmail(email);

		if (null == user || // 未注册
				!user.getPassWord().equals(passWord)) { // 密码错误
			// 提示用户名或者密码错误
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNameOrPassWordError"), HttpStatus.OK);
		}
		// 生成token，保存用户登录状态
		TokenModel model = this.tokenManager.createToken(user.getUserId());
		//去除敏感信息
        user.setPassWord("");
		user.setUserName("");
		user.setPhone("");
        user.setPayPassword("");
        user.setIdcardUrla("");
        user.setIdcardUrlb("");
        user.setWalletBtcPrivatekey("");
        user.setWalletEthPrivatekey("");
		String UserJson = JSON.toJSONString(user);
		JSONObject userObject = JSON.parseObject(UserJson);
		//初始化用户资产
		int userId=user.getUserId();
		double asset = this.cbtAssetService.getAsset(userId);
		CbtReward signIn=this.cbtRewardService.selectRewardByuserId(userId);
		if (signIn==null) {
			userObject.put("signInFlag", 0);
		}else {
			userObject.put("signInFlag", 1);
		}
		userObject.put("asset", asset);
		userObject.put("token", model.getToken());
		return new ResponseEntity<>(ResultModel.ok(userObject), HttpStatus.OK);
	}
	

	/**
	 * 用户登出
	 */
	@PostMapping(value = "/logout")
	@Authorization
	public ResponseEntity<ResultModel> logout(@RequestParam("userId") Integer userId) {
		System.out.println("userId: " + userId);
		this.tokenManager.deleteToken(userId);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		System.out.println(jsonObject);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}

	/**
	 * 用户通过手机号注册
	 *  
	 */
	@PostMapping(value = "/addUserByPhone")
	public ResponseEntity<ResultModel> addUserByPhone(@RequestParam("phone") String phone,
			@RequestParam("passWord") String passWord,@RequestParam("code") String code,
			@RequestParam("avatar") String avatar,@RequestParam("area") String area) {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);


		if(avatar==null||avatar.equals("")){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"avatarError"), HttpStatus.OK);
		}
//		 
		//验证用户输入的手机号格式
		if (Integer.valueOf(area)==86) {
			if(!phone.matches(Constants.REGEX_MOBILE)){
				return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"phoneError"), HttpStatus.OK);
			}
		}else{
			if(!phone.matches(Constants.REGEX_MOBILEs)){
				return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"phoneError"), HttpStatus.OK);
			}
		}
		
		if(!passWord.matches(Constants.REGEX_PASSWORD)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"passwordError"), HttpStatus.OK);
		}
		//验证是否已注册
		User newUser = this.userService.selectByPhoneAndCode(phone,area);
        if (null != newUser) {
        	return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userHasExists"), HttpStatus.OK);
        }
		
		User user=new User();
		//若邀请码不为空，验证用户输入的邀请码
		System.out.println("avatar$$$$$$$$:"+avatar);
		
		User tmpUser=null;
		int tmpUserId=0;
		if (avatar.trim()!=null&&avatar.trim().length()!=0) {
			if(!avatar.equals(Constants.DEFAULT_REFER_CODE)) {
				tmpUser = this.userService.selectByAvatar(avatar);
				System.out.println("tmpUser"+tmpUser);
				if(tmpUser==null) {
					return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"avatarInputError"), HttpStatus.OK);
				}
				tmpUserId=tmpUser.getUserId();
				user.setReferer(tmpUserId);
			}else {
				user.setReferer(Constants.DEFAULT_REFER_ID);
			}
		}
//		验证短信验证码
//		if(code == null || code.equals("")) {
//			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
//		}
//		String sendCode=map.get(phone);
//		  System.out.println("sendCode:"+sendCode);
//		  if(sendCode == null || sendCode.trim().isEmpty() || !sendCode.equals(code)){
//		
//			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
//		}
//		
		
		user.setPhone(phone);
		user.setPassWord(passWord);

		ResultModel resultModel = this.userService.addUserByPhone(user);
		
		System.out.println("成功添加用户%%%%%%%%%");
		Integer userId = this.userService.getUserIDbyPhone(user.getPhone());
				
		System.out.println("用户Id:"+userId);
		//用户注册成功后，在资产表中加入数据
		CbtAsset cbtAsset=new CbtAsset();
		cbtAsset.setUserId(userId);
		cbtAsset.setAsset(0.0);
		this.cbtAssetService.save(cbtAsset);
		
		CbtArea cbtArea = new CbtArea();
		cbtArea.setUserId(userId);
		cbtArea.setAccount(area);
		cbtAreaService.save(cbtArea);
		
		String resultModelJson = JSON.toJSONString(resultModel.getData());
		JSONObject resultAdd = JSON.parseObject(resultModelJson);
		// 生成token，保存用户登录状态
		TokenModel model = this.tokenManager.createToken(userId);
		user.setPassWord("");
		user.setUserName("");
		user.setMailNum("");
        user.setPayPassword("");
        user.setIdcardUrla("");
        user.setIdcardUrlb("");
        user.setWalletBtcPrivatekey("");
        user.setWalletEthPrivatekey("");
		resultAdd.put("token", model.getToken());
		map.remove(phone);
		//*********************************2019-2-20
		CbtReward cbtReward =new CbtReward();
		cbtReward.setUserId(tmpUserId);
		cbtReward.setAmount(0.0);
		//邀请奖励
		cbtReward.setFlag(2);
		cbtReward.setRewardDate(new Date());
		cbtReward.setReferee(userId);
		cbtReward.setRegisterNo(phone);
		this.cbtRewardService.save(cbtReward);
		return new ResponseEntity<>(ResultModel.ok(resultAdd), HttpStatus.OK);
	}
	
	/**
	 * 用户通过邮箱号注册
	 *  
	 */
	@PostMapping(value = "/addUserByEmail")
	public ResponseEntity<ResultModel> addUserByEmail(@RequestParam("email") String email,
			@RequestParam("passWord") String passWord,@RequestParam("code") String code,
			@RequestParam("avatar") String avatar) {
		 //语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//验证用户输入的邮箱格式
		if(!email.matches(Constants.REGEX_EMAIL)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"emailError"), HttpStatus.OK);
		}
		if(!passWord.matches(Constants.REGEX_PASSWORD)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"passwordError"), HttpStatus.OK);
		}
		//验证邮箱是否已注册
		User newUser = this.userService.selectByEmail(email);
        if (null != newUser) {
        	return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userHasExists"), HttpStatus.OK);
        }
		User user=new User();
		//若邀请码不为空，验证用户输入的邀请码
		if(avatar.equals("")) {
			System.out.println("avatar@@@@@:"+avatar);
		}
		//若邀请码不为空，验证用户输入的邀请码
		User tmpUser=null;
		int tmpUserId=0;
		if (avatar.trim()!=null&&avatar.trim().length()!=0) {
			if(!avatar.equals(Constants.DEFAULT_REFER_CODE)) {
				tmpUser = this.userService.selectByAvatar(avatar);
				System.out.println("tmpUser"+tmpUser);
				if(tmpUser==null) {
					return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"avatarInputError"), HttpStatus.OK);
				}
				tmpUserId=tmpUser.getUserId();
				user.setReferer(tmpUserId);
			}else {
				user.setReferer(Constants.DEFAULT_REFER_ID);
			}
		}
		//验证邮箱验证码
		if(code==null||code.equals("")) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
		}
		String sendCode=map.get(email);
		System.out.println("sendCode:"+sendCode);
		if(sendCode==null||sendCode.trim().isEmpty()||!sendCode.equals(code)){
		
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
		}
		
		
		user.setMailNum(email);
		user.setPassWord(passWord);
		
		ResultModel resultModel = this.userService.addUserByEmail(user);
		
		System.out.println("成功添加用户@@@@@@@@@@@");
		Integer userId = this.userService.selectByEmail(email).getUserId();
		
		//用户注册成功后，在资产表中加入数据
		CbtAsset cbtAsset=new CbtAsset();
		cbtAsset.setUserId(userId);
		cbtAsset.setAsset(0.0);
		this.cbtAssetService.save(cbtAsset);
		
		String resultModelJson = JSON.toJSONString(resultModel.getData());
		JSONObject resultAdd = JSON.parseObject(resultModelJson);
		// 生成token，保存用户登录状态
		TokenModel model = this.tokenManager.createToken(userId);
		user.setPassWord("");
		user.setUserName("");
		user.setPhone("");
        user.setPayPassword("");
        user.setIdcardUrla("");
        user.setIdcardUrlb("");
        user.setWalletBtcPrivatekey("");
        user.setWalletEthPrivatekey("");
		resultAdd.put("token", model.getToken());
		resultModel.setData(resultAdd);
		map.remove(email);
		//********************************2019-2-20
		CbtReward cbtReward =new CbtReward();
		cbtReward.setUserId(tmpUserId);
		cbtReward.setAmount(0.0);
		//邀请奖励
		cbtReward.setFlag(2);
		cbtReward.setRewardDate(new Date());
		cbtReward.setReferee(userId);
		cbtReward.setRegisterNo(email);
		this.cbtRewardService.save(cbtReward);
		return new ResponseEntity<>(resultModel, HttpStatus.OK);
	}
	
	/**
	 * 发送手机验证码
	 * @throws IOException 
	 * @throws HttpException 
	 */
	private Map<String,String>map=new Hashtable<String,String>();
	@PostMapping(value = "/sendPhoneMsg")
	public ResponseEntity<ResultModel> sendPhoneMsg(@RequestParam("phone") String phone,
			@RequestParam("type") String type,@RequestParam("code") String codes) throws Exception {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//type 为1时是注册新用户，不需要验证是否存在
		System.out.println("type$$$$$$"+type);
		if(!type.equals("1")){
			User user = this.userService.selectByPhone(phone);
			if ( user==null) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNotFound"), HttpStatus.OK);
			}
		}
		
		long nowDate = new Date().getTime();
		String str=String.valueOf(nowDate);
		String code=str.substring(9);
		map.put(phone, code);
		for (String key : map.keySet()) {
			System.out.println(key);
			System.out.println(map.get(key));
		}
		int n = 0;
		if (codes.equals("86")) {
			 n=SendPhoneMessage.sendMsg(phone,code);
		}else {
			String codePhone = codes+phone;
			 n = SendPhoneMessage.sendInternalMsg(codePhone, code);
		}
//		int n=SendPhoneMessage.sendMsg(phone,code);
		System.out.println("############n:"+n);
		JSONObject jsonObjectRet = new JSONObject();
		if(n==200) {
			jsonObjectRet.put("result", 100);
			return new ResponseEntity<>(ResultModel.ok(jsonObjectRet), HttpStatus.OK);
		}else {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"sendFail"), HttpStatus.OK);
		}
	}
	
	/**
	 * 发送国际手机验证码
	 * @throws IOException 
	 * @throws HttpException 
	 */

	@PostMapping(value = "/sendPhoneInternalMsg")
	public ResponseEntity<ResultModel> sendPhoneInternalMsg(@RequestParam("phone") String phone,
			@RequestParam("type") String type,@RequestParam("code") String codes) throws Exception {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//type 为1时是注册新用户，不需要验证是否存在
		System.out.println("type$$$$$$"+type);
		if(!type.equals("1")){
			User user = this.userService.selectByPhone(phone);
			if ( user==null) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNotFound"), HttpStatus.OK);
			}
		}
		
		long nowDate = new Date().getTime();
		String str=String.valueOf(nowDate);
		String code=str.substring(9);
		map.put(phone, code);
		for (String key : map.keySet()) {
			System.out.println(key);
			System.out.println(map.get(key));
		}
		int n = 0;
		if (codes.equals("86")) {
			 n=SendPhoneMessage.sendMsg(phone,code);
		}else {
			String codePhone = codes+phone;
			 n = SendPhoneMessage.sendInternalMsg(codePhone, code);
		}
//		int n=SendPhoneMessage.sendMsg(phone,code);
		System.out.println("############n:"+n);
		JSONObject jsonObjectRet = new JSONObject();
		if(n==200) {
			jsonObjectRet.put("result", 100);
			return new ResponseEntity<>(ResultModel.ok(jsonObjectRet), HttpStatus.OK);
		}else {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"sendFail"), HttpStatus.OK);
		}
	}
	
	
	/**
	 * 
	 * 发送邮箱验证码
	 */
	@PostMapping(value = "/sendEmailMsg")
	public ResponseEntity<ResultModel> sendEmailMsg(@RequestParam("email") String email,
			@RequestParam("type") String type) {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//type 为1时是注册新用户，不需要验证是否存在
		if(!type.equals("1")){
			User user = this.userService.selectByEmail(email);
			if ( user==null) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNotFound"), HttpStatus.OK);
			}
		}
		long nowDate = new Date().getTime();
		String str=String.valueOf(nowDate);
		String string=str.substring(9);
		map.put(email, string);
		for (String key : map.keySet()) {
			System.out.println(key);
			System.out.println(map.get(key));
		}
		try {
			Thread.sleep(3000);
			SendMail.sendMessage(email,string);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		System.out.println(email+":***"+string);
		System.out.println(jsonObject);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}

	
	/**
	 * 修改登录密码
	 */
	@PostMapping(value = "/setPassword")
	public ResponseEntity<ResultModel> setPassword(@RequestParam("phone") String phone,
			@RequestParam("passWord") String passWord,@RequestParam("code") String code,@RequestParam(value ="area", required = false) String area) {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		
		if (area==null) {
			area="86";
		}
		User user = this.userService.selectByPhoneAndCode(phone,area);
	
		int userIdbyToken = getUserIdbyToken();
//		User user = this.userService.selectByUserId(userIdbyToken);
//		User user = this.userService.selectByPhone(phone);
		User user1 = this.userService.selectByEmail(phone);
//		User user1 = this.userService.selectByUserId(userIdbyToken);
		if (user==null && user1==null) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNotFound"), HttpStatus.OK);
		}
		if(!passWord.matches(Constants.REGEX_PASSWORD)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"passwordError"), HttpStatus.OK);
		}
//		String sendCode=map.get(phone);
//		  System.out.println("sendCode:"+sendCode);
//		  
//		if(sendCode == null || sendCode.trim().isEmpty() || !sendCode.equals(code)){
//		
//			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
//		}
		ResultModel resultModel = null;
		if(user!=null) {
			
			user.setPassWord(passWord);
			Integer userId=user.getUserId();
			resultModel = this.userService.updateUser(userId, user);
		}
		if(user1!=null) {
			user1.setPassWord(passWord);
			Integer userId=user1.getUserId();
			resultModel = this.userService.updateUser(userId, user1);
		}
	
		map.remove(phone);
		return new ResponseEntity<>(resultModel, HttpStatus.OK);
	}
	
	/**
	 * 修改支付密码
	 */
	@PostMapping(value = "/setPayPassword")
	@Authorization
	public ResponseEntity<ResultModel> setPayPassword(@RequestParam("phone") String phone,
			@RequestParam("payPassword") String payPassword,
			@RequestParam("code") String code) {
		System.out.println("payPassword:"+payPassword);
		System.out.println("code:"+code);
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		//若code为-1时，是设置支付密码，不需要发送验证码，其他时候需要验证code
		int userIdbyToken = getUserIdbyToken();
		User user = this.userService.selectByUserId(userIdbyToken);
//		User user = this.userService.selectByPhone(phone);
		User user1 = this.userService.selectByEmail(phone);
//		User user1 = this.userService.selectByUserId(userIdbyToken);;
		if (user==null && user1==null) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"userNotFound"), HttpStatus.OK);
		}
		if(!payPassword.matches(Constants.REGEX_PAYPASSWORD)){
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"payPasswordError"), HttpStatus.OK);
		}
		if(!code.equals("-1")) {
			String sendCode=map.get(phone);
			System.out.println("sendCode:"+sendCode);
			if(sendCode==null||sendCode.trim().isEmpty()||!sendCode.equals(code)){
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"codeError"), HttpStatus.OK);
			}
		}
		ResultModel resultModel = null;
		if(user != null) {
			
			user.setPayPassword(payPassword);
			user.setStatus(1);
			Integer userId=user.getUserId();
			resultModel = this.userService.updateUser(userId, user);
		}
		if(user1 != null) {
			
			user1.setPayPassword(payPassword);
			user1.setStatus(1);
			Integer userId=user1.getUserId();
			resultModel = this.userService.updateUser(userId, user1);
		}
	
		map.remove(phone);
		return new ResponseEntity<>(resultModel, HttpStatus.OK);
	}
	

	/**
	 * 修改用户昵称
	 */
	@PostMapping(value = "/setNickName")
	@Authorization
	public ResponseEntity<ResultModel> setNickName(@RequestParam("userId") Integer userId,
			@RequestParam("nickName") String nickName) {
		System.out.println("userId: " + userId);
		System.out.println("nickName: " + nickName);
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		if(!nickName.matches(Constants.REGEX_NICKNAME)) {
			return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"nicknameError"), HttpStatus.OK);
		}
		User user=this.userService.selectByUserId(userId);
		user.setNickName(nickName);
		ResultModel resultModel = this.userService.updateUser(userId, user);
		return new ResponseEntity<>(resultModel, HttpStatus.OK);
	}
	
	/**
	 * 修改用户头像
	 * @throws Exception 
	 */
	@PostMapping(value = "/setPicUrl")
	@Authorization
	public ResponseEntity<ResultModel> setPicUrl(@RequestParam("userId") Integer userId,
			@RequestParam("picture") MultipartFile imageFile) {
		 //语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
        if (null == imageFile) {
            return new ResponseEntity<ResultModel>(ResultModel.error(myResourcesBundle,"imageNotEmpty"), HttpStatus.BAD_REQUEST);
        }
        String fileName = "";
        try {
            fileName = FileUtil.upload(imageFile, Constants.IMAGE_SAVE_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
	        
		User user=this.userService.selectByUserId(userId);
		user.setPicUrl("userPic/"+fileName);
		ResultModel resultModel = this.userService.updateUser(userId, user);
		return new ResponseEntity<>(resultModel, HttpStatus.OK);
	}
	


	
	/**
	 * 
	 * 用户充值
	 */
	@PostMapping(value = "/doRecharge")
	@Authorization
	public ResponseEntity<ResultModel> doRecharge(@RequestParam("userId") Integer userId,
			@RequestParam("coinId") Integer coinId) {
		//根据coinId获取location
		String coinLocation=this.cbtCoinInfoService.selectCoinLocationBycoinId(coinId);
		//获取用户钱包地址
		User user=this.userService.selectByUserId(userId);
		JSONObject coinObject = new JSONObject();
		if(coinLocation.equals("Ethereum")){
			coinObject.put("walletAddress", user.getWalletEthAddress());
		}
		if(coinLocation.equals("Bitcoin")){
			coinObject.put("walletAddress", user.getWalletBtcAddress());
		}
		if(coinLocation.equals("USDT")) {
			coinObject.put("walletAddress", user.getWalletBtcAddress());
		}
		if(coinLocation.equals("DFC")) {
			coinObject.put("walletAddress", user.getWalletBtcAddress());
		}
		return new ResponseEntity<>(ResultModel.ok(coinObject), HttpStatus.OK);
		
	}
	
	/**
	 * 用户存单列表
	 * @param userId
	 * @param page
	 * @param rows
	 * @return
	 */
	@GetMapping(value = "/getInvestListByuserId")
	@Authorization
	public ResponseEntity<ResultModel> getInvestListByuserId(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page, @RequestParam("row") Integer rows) {
		List<CbtInvest> investList = this.cbtInvestService.getInvestListByuserId(page, rows, userId);
		System.out.println("@#$%^&*:"+investList);
		JSONObject investObject = new JSONObject();
		int totalPages=this.cbtInvestService.totalPages(userId, rows);
		if(investList == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			investObject.put("investList",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		CbtCoininfo PCCoininfo = cbtCoinInfoService.selectCoinInfoBycoinSymbol("DFC");
		String coinSymbol = PCCoininfo.getCoinSymbol();
		String coinPic = PCCoininfo.getCoinUrl();
		for(CbtInvest cbtInvest : investList) {
			System.out.println("@#&&&&&&:"+cbtInvest.getCbtIncome());
			JSONObject jsonObject = new JSONObject();
//			CbtCoininfo cbtCoininfo=cbtInvest.getCbtCoininfo();
//			String coinSymbol=cbtCoininfo.getCoinSymbol();
//			String coinPic=cbtCoininfo.getCoinUrl();
			int investId=cbtInvest.getId();
			Double ethPrice = cbtInvest.getEthPrice();
			Double dfcPrice = cbtInvest.getDfcPrice();
			Double price = cbtInvest.getPrice();
			Date date=cbtInvest.getInvestDate();
			int period=cbtInvest.getInvestDuration();
			double capital=cbtInvest.getInvestAmount();
			
			//存单昨日收益
			double yesterdayIncome1=this.cbtIncomeService.selectYesterdayIncomeByInvestId(investId);
			BigDecimal decimal = new BigDecimal(Double.toString(yesterdayIncome1));
	        BigDecimal yesterdayIncome = decimal.setScale(2,BigDecimal.ROUND_DOWN);
		
			CbtIncome cbtIncome=cbtInvest.getCbtIncome();
			Double totalIncome1=cbtIncome.getIncome();
			if(totalIncome1==null) {
				totalIncome1=0.0;
			}
			BigDecimal decimal1 = new BigDecimal(Double.toString(totalIncome1));
	        BigDecimal totalIncome = decimal1.setScale(2,BigDecimal.ROUND_DOWN);
			
			//剩余可提收益
			CbtTransfer cbtTransfer=cbtInvest.getCbtTransfer();
			Double amount=cbtTransfer.getAmount();
			if(amount == null) {
				amount=0.0;
			}
			double drawIncome=totalIncome1-amount;
			
			int expire = 1;
			if (capital >= totalIncome1) {
				expire = 0;
			}
    
			jsonObject.put("id", investId);
			jsonObject.put("coinPic", coinPic);
			jsonObject.put("coinSymbol", coinSymbol);
			jsonObject.put("date", date);
			//jsonObject.put("period", period);---delete
			jsonObject.put("capital", capital);
			jsonObject.put("totalIncome", totalIncome);
			jsonObject.put("drawIncome", drawIncome);
			//jsonObject.put("restDays", restDays);--delete
			jsonObject.put("yesterdayIncome", yesterdayIncome);
			jsonObject.put("expire", expire);
			jsonObject.put("ethPrice", ethPrice);
			jsonObject.put("dfcPrice", dfcPrice);
			jsonObject.put("price", price);
			showList.add(jsonObject);
		}
	
		investObject.put("investList", showList);
		investObject.put("totalPage", totalPages);
		investObject.put("userId", userId);
		return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
	}
	
	
	//获取单个用户所有存单的当天收益
	
	@PostMapping(value = "/getTodayIncomeByuserId")
	@Authorization
	public ResponseEntity<ResultModel> getTodayIncomeByuserId(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page, @RequestParam("row") Integer rows){
		
		List<CbtIncome> cbtIncomes = this.cbtIncomeService.selectTodayIncomeByuserId(page, rows, userId);
		
		JSONObject investObject = new JSONObject();
		int totalPages=this.cbtIncomeService.totalPages(userId, rows);
		if(cbtIncomes == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			investObject.put("investList",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
		}
		
		investObject.put("totalPage", totalPages);
		investObject.put("incomesList", cbtIncomes);

		return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
		
	}
	
	/**
	 * 提取本金时获取存单状态---delete
	 */
	@PostMapping(value = "/getInvestState")
	@Authorization
	public ResponseEntity<ResultModel> getInvestState(@RequestParam("userId") Integer userId,
				@RequestParam("investId") Integer investId) {
		//语言切换基类
		String language=request.getHeader(Constants.LANGUAGE);
		 if(language == null) {
			language="language_zh"; 
		 }
		 String[]arr=language.split("_");
		 ResourceBundle myResourcesBundle =International.getLanguage(request);
		 
		JSONObject jsonObject = new JSONObject();
		CbtTransfer cbtTransfer=this.cbtTransferService.selectByInvestId(investId);
		if(cbtTransfer != null) {
			jsonObject.put("result", false);
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"error"), HttpStatus.OK);
		}
		CbtInvest cbtInvest=this.cbtInvestService.getInvestById(investId);
		System.out.println("cbtInvest%%%%:"+cbtInvest);
		if(cbtInvest == null) {
			jsonObject.put("result", false);
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"error"), HttpStatus.OK);
		}
		Date createDate=cbtInvest.getInvestDate();
		//投资周期
		int investDuration=cbtInvest.getInvestDuration();
		//投资本金
		double investAmount=cbtInvest.getInvestAmount();
		//投资币的Id
		int coinId=cbtInvest.getCoinId();
		CbtCoininfo cbtCoininfo=this.cbtCoinInfoService.selectCoinInfoBycoinId(coinId);
		String coinSymbol=cbtCoininfo.getCoinSymbol();
		//计算投资到期时间
		Calendar calendar = Calendar.getInstance();  
		calendar.setTime(createDate);  
		calendar.add(Calendar.DATE, investDuration);
		Date nowDate=new Date();
		//投资不到期不能提取本金
		if(nowDate.getTime()<calendar.getTimeInMillis()) {
			if(investDuration == 30) {
				int constantId=1;
				CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
				int discountRate=cbtConstant.getNum1();
				//提前提取本金扣除的本金
				double deductAmount=investAmount*discountRate/100;
				BigDecimal decimal = new BigDecimal(Double.toString(deductAmount));
		        System.out.println(decimal);
		        BigDecimal number = decimal.setScale(4,BigDecimal.ROUND_DOWN);
		        String amount=SubZero.subZeroAndDot(number);
				investAmount=investAmount*(100-discountRate)/100;
				jsonObject.put("expire", 0);
				
				if(arr[1].equals("zh")){
				jsonObject.put("result", "提前提取本金将收取"+discountRate+"%的本金"
						+amount+coinSymbol+"作为手续费");
				}
				if(arr[1].equals("tw")){
					jsonObject.put("result", "提前提取本金將收取"+discountRate+"%的本金"
							+amount+coinSymbol+"作為手續費");
				}
				if(arr[1].equals("ko")){
					jsonObject.put("result", "미리 본금을 인출하면"+ discountRate+"%의 본금"
							+amount+coinSymbol+"를 수속비료로 받습니다");
				}
				if(arr[1].equals("en")){
					jsonObject.put("result", discountRate+"% of the principal"+amount+coinSymbol+"will be charged as "
							+ "handling fee for early withdrawal of principal");
				}
				
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			if(investDuration == 60) {
				int constantId=2;
				CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
				int discountRate=cbtConstant.getNum1();
				//提前提取本金扣除的本金
				double deductAmount=investAmount*discountRate/100;
				BigDecimal decimal = new BigDecimal(Double.toString(deductAmount));
		        System.out.println(decimal);
		        BigDecimal number = decimal.setScale(4,BigDecimal.ROUND_DOWN);
		        String amount=SubZero.subZeroAndDot(number);
				investAmount=investAmount*(100-discountRate)/100;
				jsonObject.put("expire", 0);
				
				if(arr[1].equals("zh")){
				jsonObject.put("result", "提前提取本金将收取"+discountRate+"%的本金"
						+amount+coinSymbol+"作为手续费");
				}
				if(arr[1].equals("tw")){
					jsonObject.put("result", "提前提取本金將收取"+discountRate+"%的本金"
							+amount+coinSymbol+"作為手續費");
				}
				if(arr[1].equals("ko")){
					jsonObject.put("result", "미리 본금을 인출하면"+ discountRate+"%의 본금"
							+amount+coinSymbol+"를 수속비료로 받습니다");
				}
				if(arr[1].equals("en")){
					jsonObject.put("result", discountRate+"% of the principal"+amount+coinSymbol+"will be charged as "
							+ "handling fee for early withdrawal of principal");
				}
				
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			if(investDuration == 90) {
				int constantId=3;
				CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
				int discountRate=cbtConstant.getNum1();
				//提前提取本金扣除的本金
				double deductAmount=investAmount*discountRate/100;
				BigDecimal decimal = new BigDecimal(Double.toString(deductAmount));
		        System.out.println(decimal);
		        BigDecimal number = decimal.setScale(4,BigDecimal.ROUND_DOWN);
		        String amount=SubZero.subZeroAndDot(number);
				investAmount=investAmount*(100-discountRate)/100;
				jsonObject.put("expire", 0);
				
				if(arr[1].equals("zh")){
				jsonObject.put("result", "提前提取本金将收取"+discountRate+"%的本金"
						+amount+coinSymbol+"作为手续费");
				}
				if(arr[1].equals("tw")){
					jsonObject.put("result", "提前提取本金將收取"+discountRate+"%的本金"
							+amount+coinSymbol+"作為手續費");
				}
				if(arr[1].equals("ko")){
					jsonObject.put("result", "미리 본금을 인출하면"+ discountRate+"%의 본금"
							+amount+coinSymbol+"를 수속비료로 받습니다");
				}
				if(arr[1].equals("en")){
					jsonObject.put("result", discountRate+"% of the principal"+amount+coinSymbol+"will be charged as "
							+ "handling fee for early withdrawal of principal");
				}
				
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			if (investDuration != 30 && investDuration != 60 && investDuration != 90) {
				jsonObject.put("expire", 0);
				jsonObject.put("result", "提前提取本金将收取30%的本金作为手续费");
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			
		}
			jsonObject.put("expire", 1);
			jsonObject.put("result", "存单已到期");
			return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}
	
	
	/**
	 * 提取本金或收益
	 * @param userId
	 * @param type
	 * @param investId
	 * @return---delete
	 */
	@PostMapping(value = "/drawCapitalOrIncome")
	@Authorization
	public ResponseEntity<ResultModel> drawCapitalOrIncome(@RequestParam("userId") Integer userId,
			@RequestParam("type") String type, @RequestParam("investId") Integer investId) {
		//提取类型:0 代表收益;1 代表本金
		JSONObject jsonObject = new JSONObject();
		//提取本金
		if(type.equals("1")) {
			CbtTransfer cbtTransfer2=this.cbtTransferService.selectByInvestId(investId);
			if(cbtTransfer2 != null) {
				jsonObject.put("result", false);
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			CbtInvest cbtInvest=this.cbtInvestService.getInvestById(investId);
			if(cbtInvest==null) {
				jsonObject.put("result", false);
				return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
			}
			Date createDate=cbtInvest.getInvestDate();
			//投资周期
			int investDuration=cbtInvest.getInvestDuration();
			//投资本金
			double investAmount=cbtInvest.getInvestAmount();
			//投资币的Id
			int coinId=cbtInvest.getCoinId();
			//计算投资到期时间
			Calendar calendar = Calendar.getInstance();  
			calendar.setTime(createDate);  
			calendar.add(Calendar.DATE, investDuration);
			Date nowDate=new Date();
			//投资不到期不能提取本金
			double deductAmount=0.0;
			if(nowDate.getTime()<calendar.getTimeInMillis()) {
				if(investDuration == 30) {
					int constantId=1;
					CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
					int discountRate=cbtConstant.getNum1();
					//提前提取本金扣除的本金
					deductAmount=investAmount*discountRate/100;
					investAmount=investAmount*(100-discountRate)/100;
				}
				if(investDuration == 60) {
					int constantId=2;
					CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
					int discountRate=cbtConstant.getNum1();
					//提前提取本金扣除的本金
					deductAmount=investAmount*discountRate/100;
					investAmount=investAmount*(100-discountRate)/100;
					
				}
				if(investDuration == 90) {
					int constantId=3;
					CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(constantId);
					int discountRate=cbtConstant.getNum1();
					//提前提取本金扣除的本金
					deductAmount=investAmount*discountRate/100;
					investAmount=investAmount*(100-discountRate)/100;
				}
			}
			//插入本金
			CbtTransfer cbtTransfer=new CbtTransfer();
			cbtTransfer.setInvestId(investId);
			cbtTransfer.setAmount(investAmount);
			cbtTransfer.setFee(deductAmount);
			cbtTransfer.setTransferDate(new Date());
			cbtTransfer.setTransferType(1);
			cbtTransfer.setUserId(userId);
			this.cbtTransferService.save(cbtTransfer);
			//本金返还用户充值表
			CbtRecharge cbtRecharge=new CbtRecharge();
			cbtRecharge.setCoinId(coinId);
			cbtRecharge.setUserId(userId);
			cbtRecharge.setAmount(investAmount);
			cbtRecharge.setRechargeDate(new Date());
			cbtRecharge.setBlockNum(0);
			this.cbtRechargeService.save(cbtRecharge);
		
		}
		jsonObject.put("result", true);
		System.out.println(jsonObject);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}
	
	
	/**
	 * 首页收益信息
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/getIncomeByuserId")
	@Authorization
	public ResponseEntity<ResultModel> getIncomeByuserId(@RequestParam("userId") Integer userId) {
		CbtIncome cbtIncome=cbtIncomeService.getIncomeByuserId(userId);
		JSONObject incomeObject = new JSONObject();
//		if(cbtIncome==null){
//			incomeObject.put("totalIncome", 0);
//			incomeObject.put("yesterdayIncome", 0);
//			return new ResponseEntity<>(ResultModel.ok(incomeObject), HttpStatus.OK);
//		}else {
			//用户存单总收益
			double totalIncome=this.cbtIncomeService.selectTotalIncomeByuserId(userId);
			//用户总的签到奖励
			double totalReward=this.cbtRewardService.selectTotalRewardByuserId(userId);
			//用户总的邀请奖励

//			double totalInvited = this.cbtInvestService.selectAllInvestByuserId(userId)/Constants.AKB_INVEST_RATIO*0.1;
			double totalInvited = this.cbtInvitedIncomeService.selectInvIncomeByuserId(userId);
			double selectDirectIncomeByuserId = cbtInvitedIncomeService.selectDirectIncomeByuserId(userId);
			//用户总的提现数量
//			double totalDraw=this.cbtDrawService.selectTotalDrawByuserId(userId);	
			
//			double totalDraw=this.cbtExchangeService.selectTotalExchangeByuserId(userId);
			/**用户兑换票权总支出
			double totalCount=this.cbtVoteRechargeService.selectTotalCountByuserId(userId);*/	
			//用户最新的资产数
//			double newAsset=totalIncome+totalReward+totalInvited-totalDraw;
			
			double newAsset=totalIncome+totalReward+totalInvited+selectDirectIncomeByuserId;

			double yesterDayIncome0 = this.cbtIncomeService.selectYesterdayIncomeByuserId(userId);
//			double yesterdayIncome1 = this.cbtInvestService.selectYesterdayRewardByuserId(userId)/Constants.AKB_INVEST_RATIO*0.1;
			double yesterdayIncome1 = this.cbtInvitedIncomeService.getYesterdayInvIncomeByUserId(userId);
			double yesterdayInvest = this.cbtInvitedIncomeService.getYesterdayIncomeByUserId(userId);
			
			double allyesterdayIncome = yesterdayIncome1 + yesterdayInvest+yesterDayIncome0;
			BigDecimal decimal = new BigDecimal(Double.toString(newAsset));
	        BigDecimal alltotalIncome = decimal.setScale(2,BigDecimal.ROUND_DOWN);
	        
			BigDecimal decimal2 = new BigDecimal(Double.toString(allyesterdayIncome));
	        BigDecimal yesterdayIncome = decimal2.setScale(2,BigDecimal.ROUND_DOWN);
	        
			incomeObject.put("totalIncome", alltotalIncome);
			incomeObject.put("yesterdayIncome", yesterdayIncome);
			return new ResponseEntity<>(ResultModel.ok(incomeObject), HttpStatus.OK);
//		}
	}
	
	/**
	 * 获取用户资产
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/getAssetMsgByuserId")
	@Authorization
	public ResponseEntity<ResultModel> getAssetMsgByuserId(@RequestParam("userId") Integer userId) {
		//用户存单总收益
		double totalIncome=this.cbtIncomeService.selectTotalIncomeByuserId(userId);
		//用户总的签到奖励
		double totalReward=this.cbtRewardService.selectTotalRewardByuserId(userId);
		//用户总的邀请奖励
//		double totalInvited=this.cbtInvitedIncomeService.getAllRewardByuserId(userId);
//		double totalInvited=this.cbtInvitedIncomeService.getAllIncomeByUserId(userId);
//		double totalInvited = this.cbtInvestService.selectAllInvestByuserId(userId)/Constants.AKB_INVEST_RATIO*0.1;
		double totalInvited = this.cbtInvitedIncomeService.selectInvIncomeByuserId(userId);
		double selectDirectIncomeByuserId = cbtInvitedIncomeService.selectDirectIncomeByuserId(userId);
		//用户总的提现数量
		double totalDraw=this.cbtExchangeService.selectTotalExchangeByuserId(userId);
		
		/**用户兑换票权总支出
		double totalCount=this.cbtVoteRechargeService.selectTotalCountByuserId(userId);*/
		
		double asset2 =this.cbtDrawService.selectTotalDrawByuserId(userId);
		
		//用户最新的资产数
		double newAsset=totalIncome+totalReward+totalInvited+selectDirectIncomeByuserId-totalDraw-asset2;
		int start = 0 ;
		InvTree selectInvTreebyUserId = this.invTreeService.selectInvTreebyUserId(userId);
		if (selectInvTreebyUserId!=null) {
			start = selectInvTreebyUserId.getUserStar();
		}
		
		CbtAsset cbtAsset=this.cbtAssetService.selectAssetByuserId(userId);
		cbtAsset.setAsset(newAsset);
		this.cbtAssetService.updateAsset(userId, cbtAsset);
		
		JSONObject assetObject = new JSONObject();
		double asset1 = cbtAssetService.getAsset(userId);
//		double asset2 =this.cbtDrawService.selectTotalDrawByuserId(userId);
//		
//		double assets = asset1-asset2;
		
		
		BigDecimal decimal = new BigDecimal(Double.toString(asset1));
        BigDecimal asset = decimal.setScale(2,BigDecimal.ROUND_DOWN);
        System.out.println("asset=>"+asset);
		assetObject.put("asset", asset);
		assetObject.put("userStar", start);
		return new ResponseEntity<>(ResultModel.ok(assetObject), HttpStatus.OK);
	}
	
	/**
	 * 抬头消息 
	 * @param type
	 * @param page
	 * @param rows
	 * @return
	 */
	@GetMapping(value = "/getNews")
	@Authorization
	public ResponseEntity<ResultModel> getNews(@RequestParam("type") String type,
			@RequestParam("page") Integer page, @RequestParam("row") Integer rows) {
		 //语言切换基类
		 String language=request.getHeader(Constants.LANGUAGE);
		 if(language == null) {
			language="language_zh"; 
		 }
		 String[]arr=language.split("_");
		 System.out.println("type=>"+type);
		//type 1 为首页，2 为更多
		JSONObject allNews = new JSONObject();
		
		if(type.equals("1")) {
			List<CbtNews> getOneNews = null;
			if(arr[1].equals("zh")) {
				int languageFlag=1;
				getOneNews=this.cbtNewsService.getOneNews(page, rows,languageFlag);
			}
			if(arr[1].equals("en")) {
				int languageFlag=2;
				getOneNews=this.cbtNewsService.getOneNews(page, rows,languageFlag);
			}
			if(arr[1].equals("tw")) {
				int languageFlag=3;
				getOneNews=this.cbtNewsService.getOneNews(page, rows,languageFlag);
			}
			if(arr[1].equals("ko")) {
				int languageFlag=4;
				getOneNews=this.cbtNewsService.getOneNews(page, rows,languageFlag);
			}
			System.out.println(getOneNews);
			allNews.put("newsInfo", getOneNews);
			return new ResponseEntity<>(ResultModel.ok(allNews), HttpStatus.OK);
		}else {
			System.out.println("type=2=>news");
			List<CbtNews> getAllNews = null;
			if(arr[1].equals("zh")) {
				int languageFlag=1;
				getAllNews=this.cbtNewsService.getAllNews(page, rows,languageFlag);
			}
			if(arr[1].equals("en")) {
				int languageFlag=2;
				getAllNews=this.cbtNewsService.getAllNews(page, rows,languageFlag);
			}
			if(arr[1].equals("tw")) {
				int languageFlag=3;
				getAllNews=this.cbtNewsService.getAllNews(page, rows,languageFlag);
			}
			if(arr[1].equals("ko")) {
				int languageFlag=4;
				getAllNews=this.cbtNewsService.getAllNews(page, rows,languageFlag);
			}
			int totalPage=this.cbtNewsService.totalPages(rows);
			System.out.println("totalPage=>"+totalPage);
			if(getAllNews == null || page > totalPage){
				JSONArray jsonArray = new JSONArray();
				allNews.put("newsInfo", jsonArray);
				return new ResponseEntity<>(ResultModel.ok(allNews), HttpStatus.OK);
			}
			System.out.println("######=news");
			allNews.put("totalPage", totalPage);
			allNews.put("newsInfo", getAllNews);
			return new ResponseEntity<>(ResultModel.ok(allNews), HttpStatus.OK);
		
		}
	}
	
	/**
	 * 首页币种信息
	 * @param userId
	 * @return---ok
	 * 
	 */
//	@GetMapping(value = "/getCoinInfoByuserId")
//	@Authorization
//	public ResponseEntity<ResultModel> getCoinInfoByuserId(@RequestParam("userId") Integer userId,
//			@RequestParam("page") Integer page, @RequestParam("row") Integer rows) {
//		int n=this.cbtCoinInfoService.selectCoinCount();
//		int totalPages=0;
//		if(n%rows == 0) {
//			totalPages=n/rows;
//		}
//		if(n%rows != 0) {
//			totalPages=n/rows+1;
//		}
//		List<CbtCoininfo>list=cbtCoinInfoService.selectCoinList(page, rows,userId);
//		
//		List<JSONObject> showList=new ArrayList<>();
//		for(CbtCoininfo coin:list) {
//			JSONObject jsonObject = new JSONObject();
//			CbtRecharge cbtRecharge=coin.getCbtRecharge();
//			//币的个数
//			Double coinAmount=cbtRecharge.getAmount();
//			if(coinAmount==null) {
//				coinAmount=0.0;
//			}
//			BigDecimal decimal = new BigDecimal(Double.toString(coinAmount));
//	        BigDecimal amount = decimal.setScale(4,BigDecimal.ROUND_DOWN);
//	        
//	        System.out.println("amount:"+amount);
//	        
//			int coinId=coin.getCoinId();
//			String picUrl=coin.getCoinUrl();
//			String coinSymbol=coin.getCoinSymbol();
//			if (!coinSymbol.equals("AKB")) {
//				continue;
//			}
//			//获取币种美金价格
//			String price1=coin.getCoinPriceUsdt();
//			System.out.println("price:"+price1);
//			double price=Double.parseDouble(price1);
//			double totalPrice=coinAmount*price;
//			BigDecimal decimal2 = new BigDecimal(Double.toString(totalPrice));
//	        BigDecimal coinPrice = decimal2.setScale(2,BigDecimal.ROUND_DOWN);
//		
//	        System.out.println("totalPrice=>"+coinPrice);
//	        
//			jsonObject.put("coinId", coinId);
//			jsonObject.put("coinSymbol", coinSymbol);
//			jsonObject.put("coinAmount", amount);
//			jsonObject.put("coinPic", picUrl);
//			jsonObject.put("coinPrice", coinPrice);
//
//			showList.add(jsonObject);
//		}
//		JSONObject newObject = new JSONObject();
//		newObject.put("userId", userId);
//		newObject.put("coinInfo", showList);
//		newObject.put("totalPages", totalPages);
//		if(page>totalPages) {
//			JSONArray jsonArray = new JSONArray();
//			newObject.put("coinInfo", jsonArray);
//			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
//		}
//		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
//	}
	
	/**
     * 首页币种信息
     *
     * @param userId
     * @return---ok
     */

    @GetMapping(value = "/getCoinInfoByuserId")
    @Authorization
    public ResponseEntity<ResultModel> getCoinInfoByuserId(@RequestParam("userId") Integer userId,
                                                           @RequestParam("page") Integer page, @RequestParam("row") Integer rows) {
        int n = this.cbtCoinInfoService.selectCoinCount();
        int totalPages = 0;
        if (n % rows == 0) {
            totalPages = n / rows;
        }
        if (n % rows != 0) {
            totalPages = n / rows + 1;
        }
        User user = userService.selectUserById(userId);
        CbtCoininfo AKBCoininfo = cbtCoinInfoService.selectCoinInfoBycoinSymbol("AKB");
        CbtCoininfo PCCoininfo = cbtCoinInfoService.selectCoinInfoBycoinSymbol("DFC");
        CbtCoininfo USDTCoininfo=cbtCoinInfoService.selectCoinInfoBycoinSymbol("USDT");
      


        List<JSONObject> showList = new ArrayList<>();

        //AKB
        double AKBAmount = cbtRechargeService.getRechargeAmount(userId, AKBCoininfo.getCoinId());
        Double coinPriceUsdt = Double.valueOf(AKBCoininfo.getCoinPriceUsdt());
        double totalPrice = AKBAmount * coinPriceUsdt;
        BigDecimal decimal2 = new BigDecimal(Double.toString(totalPrice));
        BigDecimal coinPrice = decimal2.setScale(4, BigDecimal.ROUND_DOWN);
        String picUrl = AKBCoininfo.getCoinUrl();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("coinId", AKBCoininfo.getCoinId());
        jsonObject.put("coinSymbol", AKBCoininfo.getCoinSymbol());
        jsonObject.put("coinAmount", AKBAmount);
        jsonObject.put("coinPic", picUrl);
        jsonObject.put("coinPrice", coinPrice);
        showList.add(jsonObject);
        
        //USDT
//        double USDTAmount = cbtRechargeService.getRechargeAmount(userId, USDTCoininfo.getCoinId());
//        Double USDTcoinPrice = Double.valueOf(USDTCoininfo.getCoinPriceRmb());
//        double totalPrice1=USDTAmount*USDTcoinPrice;
//        BigDecimal decimal5 = new BigDecimal(Double.toString(totalPrice1));
//        BigDecimal coinPrice1 = decimal5.setScale(4,BigDecimal.ROUND_DOWN);
//        String picUrl2=USDTCoininfo.getCoinUrl();
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("coinId", USDTCoininfo.getCoinId());
//        jsonObject2.put("coinSymbol", USDTCoininfo.getCoinSymbol());
//        jsonObject2.put("coinAmount", USDTAmount);
//        jsonObject2.put("coinPic", picUrl2);
//        jsonObject2.put("coinPrice", coinPrice1);
//        showList.add(jsonObject2);
// 

        //DFC
        double totalIncome = this.cbtIncomeService.selectTotalIncomeByuserId(userId);
        //用户总的邀请奖励
        double totalInvited = this.cbtInvitedIncomeService.selectInvIncomeByuserId(userId);
        //用户极差奖励
        double selectDirectIncomeByuserId = cbtInvitedIncomeService.selectDirectIncomeByuserId(userId);
        //用户PC金额
        double rechargeAmount = cbtRechargeService.getRechargeAmount(userId, PCCoininfo.getCoinId());
        double PCAmount = totalIncome + rechargeAmount + selectDirectIncomeByuserId + totalInvited;

        BigDecimal decimal3 = new BigDecimal(Double.toString(PCAmount));
        BigDecimal PCcoinPrice = decimal3.setScale(4, BigDecimal.ROUND_DOWN);

        Double coinPCPriceUsdt = Double.valueOf(PCCoininfo.getCoinPriceUsdt());
        double totalPCPrice = PCAmount * coinPCPriceUsdt;
        BigDecimal decimal4 = new BigDecimal(Double.toString(totalPCPrice));
        BigDecimal coinPCPrice = decimal4.setScale(4, BigDecimal.ROUND_DOWN);
        String picUrl1 = PCCoininfo.getCoinUrl();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("coinId", PCCoininfo.getCoinId());
        jsonObject1.put("coinSymbol", PCCoininfo.getCoinSymbol());
        jsonObject1.put("coinAmount", PCcoinPrice);
        jsonObject1.put("coinPic", picUrl1);
        jsonObject1.put("coinPrice", coinPCPrice);
        showList.add(jsonObject1);

        JSONObject newObject = new JSONObject();
        newObject.put("userId", userId);
        newObject.put("coinInfo", showList);

        return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
    }
	
	
	/**
	 * 
	 * 用户兑换
	 * 
	 */
	@DuplicateSubmitToken
	@PostMapping(value = "/drawMoney")
	@Authorization
	public ResponseEntity<ResultModel> drawMoney(@RequestParam("userId") Integer userId, @RequestParam("value") double value) {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		if (value<=0) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"zeroValue"), HttpStatus.OK);
		}
		 
		String regex = "^[A-Za-z0-9]{43}$";
		User user=this.userService.selectByUserId(userId);
		String walleatAdress = user.getWalletEthAddress();
		//身份证是否已验证
		if (!walleatAdress.matches(regex)) {
			//钱包地址检查错误
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"wrongWalletAddress"), HttpStatus.OK);
		}
		//用户资产总数
		double drawAmount=this.cbtAssetService.getAsset(userId);
		
		System.out.println("++++++++++++++++++++++++++++++++++++++++1===="+drawAmount);
		if(value > drawAmount){
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"drawMoneyError"), HttpStatus.OK);
		}
		//提现成功，更新用户资产表
		CbtAsset cbtAsset=this.cbtAssetService.selectAssetByuserId(userId);
		boolean freezeFlag=cbtAsset.getFreezeFlag();
		if(freezeFlag) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"error"), HttpStatus.OK);
		}
		cbtAsset.setAsset(drawAmount-value);
		System.out.println("++++++++++++++++++++++++++++++++++++++++2===="+cbtAsset.getAsset());
		
		this.cbtAssetService.updateAsset(userId, cbtAsset);
		
		System.out.println("++++++++++++++++++++++++++++++++++++++++3==="+cbtAssetService.getAsset(userId));
		
		
		//兑换成ETH的个数
		WalletProcess walletProcess = new WalletProcess();
		//提现2%的手续费
		CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(1);
		String rate=cbtConstant.getString1();
		double feeRatio =Double.parseDouble(rate)/100;
		System.out.println("feeRatio:"+feeRatio);		
		
		CbtCoininfo cbtCoininfo=cbtCoinInfoService.selectCoinInfoBycoinSymbol("AKB");
		double ethPrice = cbtCoininfo.getCoinPriceRmb();
		System.out.println("ethPrice:"+ethPrice);
		
		double fee = value*feeRatio;
		
		double ethWithdrawCnt =  (value - fee);/// (ethPrice);
		System.out.println("ethWithdrawCnt:"+ethWithdrawCnt);
		//进行更新用户的
		CbtRecharge cbtRecharge=new CbtRecharge();
		cbtRecharge.setCoinId(cbtCoininfo.getCoinId());
		cbtRecharge.setUserId(userId);
		//对应AKB增加
		cbtRecharge.setAmount(ethWithdrawCnt);
		cbtRecharge.setRechargeDate(new Date());
		cbtRecharge.setBlockNum(0);
		this.cbtRechargeService.save(cbtRecharge);

		//给用户提现表插入数据
		CbtExchange cbtExchange=new CbtExchange();
		cbtExchange.setAccount(walleatAdress);
		cbtExchange.setAmount(value);
//		cbtExchange.setDrawHash(hash);
		cbtExchange.setEthPrice(ethPrice);
		cbtExchange.setFee(fee);
		cbtExchange.setDrawDate(new Date());
		cbtExchange.setUserId(userId);
		//提现状态: 0 代表提现失败;1 代表提现成功;2 代表提现中...;
		cbtExchange.setStatus(1);
		this.cbtExchangeService.save(cbtExchange);
		
		//增加提现记录
		int drawId=this.cbtExchangeService.selectMaxExchangeId();
		CbtPayLog cbtPayLog=new CbtPayLog();
		cbtPayLog.setCbtAmount(value);
		cbtPayLog.setDrawDate(new Date());
		cbtPayLog.setDrawHash("-1");
		cbtPayLog.setDrawId(drawId);
		cbtPayLog.setEthAmount(ethWithdrawCnt);
		cbtPayLog.setEthPrice(ethPrice);
		cbtPayLog.setFee(fee);
		cbtPayLog.setUserId(userId);
		cbtPayLog.setWalletAddress(walleatAdress);
		cbtPayLog.setFlag(1);
		this.cbtPayLogService.save(cbtPayLog);
	
		double newAsset=this.cbtAssetService.getAsset(userId);
		JSONObject newObject = new JSONObject();
		newObject.put("asset",newAsset);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	

		
	}
	
	
	/**
	 * 提现手续费率
	 */
	@GetMapping(value = "/drawRate")
	@Authorization
	public ResponseEntity<ResultModel> drawRate() {
		CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(1);
		String drawRate=cbtConstant.getString1();
		CbtCoininfo cbtCoininfo=this.cbtCoinInfoService.selectCoinInfoBycoinSymbol("AKB");
		double ETHPrice=cbtCoininfo.getCoinPriceRmb();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("drawRate",drawRate+"%");
		jsonObject.put("ETHPrice",ETHPrice);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}

	
	/**
	 * 用户兑换记录
	 * @param userId
	 * @param page
	 * @param rows
	 * @return
	 */
	@GetMapping(value = "/getDrawRecord")
	@Authorization
	public ResponseEntity<ResultModel> getDrawRecord(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		List<CbtExchange> drawRecord=cbtExchangeService.selectExchangeRecordByuserId(page, rows, userId);
		JSONObject newObject = new JSONObject();
		int totalPages=this.cbtExchangeService.totalPages(userId, rows);
		if(drawRecord==null ||page>totalPages) {
			JSONArray jsonArray = new JSONArray();
			newObject.put("drawRecord",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(CbtExchange cbtExchange:drawRecord) {
			JSONObject jsonObject = new JSONObject();
			String account=cbtExchange.getAccount();
			Date exchangeDate=cbtExchange.getDrawDate();
			Double amount=cbtExchange.getAmount();
			int status=cbtExchange.getStatus();
			if(amount==null) {
				amount=0.0;
			}
			jsonObject.put("account", account);
			jsonObject.put("drawDate", exchangeDate);
			jsonObject.put("amount", amount);
			jsonObject.put("status", status);
			showList.add(jsonObject);
		}
		
		
		newObject.put("drawRecord", showList);
		newObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	
			
	}
	
	/**
	 * 用户提现记录
	 * @param userId
	 * @param page
	 * @param rows
	 * @return
	 */
	@GetMapping(value = "/getDrawRecordxxx")
	@Authorization
	public ResponseEntity<ResultModel> getDrawRecordxxx(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		List<CbtDraw>drawRecord=cbtDrawService.selectDrawRecordByuserId(page, rows, userId);
		JSONObject newObject = new JSONObject();
		int totalPages=this.cbtDrawService.totalPages(userId, rows);
		if(drawRecord==null ||page>totalPages) {
			JSONArray jsonArray = new JSONArray();
			newObject.put("drawRecord",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(CbtDraw cbtDraw:drawRecord) {
			JSONObject jsonObject = new JSONObject();
			String account=cbtDraw.getAccount();
			Date drawDate=cbtDraw.getDrawDate();
			Double amount=cbtDraw.getAmount();
			int status=cbtDraw.getStatus();
			if(amount==null) {
				amount=0.0;
			}
			jsonObject.put("account", account);
			jsonObject.put("drawDate", drawDate);
			jsonObject.put("amount", amount);
			jsonObject.put("status", status);
			showList.add(jsonObject);
		}
		
		
		newObject.put("drawRecord", showList);
		newObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	
		
		
	}
	
	
	/**
	 * 投资利率
	 */
	@GetMapping(value = "/getInvestRatio")
	@Authorization
	public ResponseEntity<ResultModel> getInvestRatio(@RequestParam("userId") Integer userId) {
		int start = this.userService.getUserStart(userId);
		double minerRatio = this.cbtMinerRatioService.getRatioByLevel(start);
		JSONObject newObject = new JSONObject();
		newObject.put("ratio",minerRatio);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	
	}
	
	
	
	
	
	/**
	 * 用户投资
	 * @param userId
	 * @param coinId
	 * @param value
	 * @param day
	 * @return
	 */
	@DuplicateSubmitToken
	@PostMapping(value = "/doInvest")
	@Authorization
	public ResponseEntity<ResultModel> doInvest(@RequestParam("userId") Integer userId,
			@RequestParam("coinId") Integer coinId,
			@RequestParam("value") double value, @RequestParam("day") Integer day) {
		 //语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		User selectByUserId = userService.selectByUserId(userId);
		if (selectByUserId.getStatus()==2) {
			 //钱包地址检查错误
			   return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"investError"), HttpStatus.OK);
		}
		
		 CbtCoininfo coinInfo = this.cbtCoinInfoService.selectCoinInfoBycoinId(coinId);
		 Double coinPriceRmb = coinInfo.getCoinPriceRmb();
		 CbtConstant cbtConstant2=this.cbtConstantService.selectConstantById(7);
		 if(coinPriceRmb<cbtConstant2.getNum2()){
			 coinPriceRmb = cbtConstant2.getNum2();
		 }
		 if(coinPriceRmb>cbtConstant2.getNum3().doubleValue()){
			 coinPriceRmb = cbtConstant2.getNum3().doubleValue();
		 }
		 
		 
		 BigDecimal b1 = new BigDecimal(value);
         BigDecimal b2 = new BigDecimal(coinPriceRmb);
		 BigDecimal divide = b1.multiply(b2);
		 CbtCoininfo coinInfo1 = this.cbtCoinInfoService.selectCoinInfoBycoinId(10000016);
		 Double coinPriceRmb2 = coinInfo1.getCoinPriceRmb();
		 CbtConstant cbtConstant1=this.cbtConstantService.selectConstantById(6);
		 if(coinPriceRmb2<cbtConstant1.getNum2()){
			 coinPriceRmb2 = cbtConstant1.getNum2();
		 }
		 if(coinPriceRmb2>cbtConstant1.getNum3().doubleValue()){
			 coinPriceRmb2 = cbtConstant1.getNum3().doubleValue();
		 }
		 
		 BigDecimal b3 = new BigDecimal(coinPriceRmb2);
		 double doubleValue = divide.divide(b3, 4,BigDecimal.ROUND_DOWN).doubleValue();
		 
		double selectAllNoInvestByuserId = cbtInvestService.selectAllPriceByuserId(userId);
		CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(5);
		double investValue = cbtConstant.getNum1()*doubleValue;
		int count = cbtInvestService.countInvestsByuserId(userId);
		if(count<1){
			if (value*coinPriceRmb<5000) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"investvalueError"), HttpStatus.OK);
			}
		}
		
		if (selectAllNoInvestByuserId+value*coinPriceRmb>50100) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"valueMore"), HttpStatus.OK);
		}
		
		 
		System.out.println("$$$$$$$$$$$$$$$$$$=="+value);
		if (value <= 0) {
			// 金额非负
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"zeroValue"), HttpStatus.OK);
		}
		//获得用户钱包资产
		double amount=cbtRechargeService.getRechargeAmount(userId, coinId);
		System.out.println("$$$$$$$$$$$$$$$$$$"+amount);
		if(value > amount){
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"capitalNotEnough"), HttpStatus.OK);
		}
		//单笔投资需大于5000 AKB
//		String price1=this.cbtCoinInfoService.selectCoinInfoBycoinId(coinId).getCoinPriceUsdt();
//		
//		double price=Double.parseDouble(price1);
//		double totalPrice=price*value;
//		if(value < Constants.MIN_INVEST_MONEY || value > Constants.MAX_INVEST_MONEY){
//			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"investMoneyError"), HttpStatus.OK);
//		}
		
		//更新用户投资表
		CbtInvest cbtInvest=new CbtInvest();
		cbtInvest.setCoinId(coinId);
		cbtInvest.setInvestAmount(investValue);
		cbtInvest.setInvestDate(new Date());
		cbtInvest.setInvestDuration(day);
		cbtInvest.setUserId(userId);
		cbtInvest.setExtractFlag(2);
		cbtInvest.setEthPrice(coinPriceRmb);
		cbtInvest.setPrice(value);
		cbtInvest.setDfcPrice(coinPriceRmb2);
		cbtInvest.setRatio(cbtConstant.getNum1());
		this.cbtInvestService.save(cbtInvest);
		//更新用户充值表
		CbtRecharge cbtRecharge=new CbtRecharge();
		cbtRecharge.setCoinId(coinId);
		cbtRecharge.setUserId(userId);
		//用户币减少
		cbtRecharge.setAmount(-value);
		cbtRecharge.setRechargeDate(new Date());
		cbtRecharge.setBlockNum(0);
		this.cbtRechargeService.save(cbtRecharge);
		
		//信息返回
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		
		CbtUserUpdate cbtUserUpdate = new CbtUserUpdate();
		cbtUserUpdate.setMemberId(userId.longValue());
		cbtUserUpdate.setInvestId(cbtInvest.getId());
		cbtUserUpdate.setStatus(2);
		cbtUserUpdateMapperService.save(cbtUserUpdate);
		
			WalletProcess walletProcess = new WalletProcess();
			WalletAccount walletAccount = null;
			if (coinInfo.getCoinSymbol().equals("AKB")) {
				walletAccount = walletProcess.DoAKBdistribute(value);
			}else {
				walletAccount = walletProcess.DoUSDTdistribute(value);
			} 
		
		invitationTreeService.doTaskOne();

		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);	
	}
	
	/**
	 * 推荐奖励率
	 */
	@PostMapping(value = "/getRewardRate")
	@Authorization
	public ResponseEntity<ResultModel> getRewardRate() {
		CbtConstant cbtConstant1=this.cbtConstantService.selectConstantById(1);
		CbtConstant cbtConstant2=this.cbtConstantService.selectConstantById(2);
		String rewardRate1=cbtConstant1.getString2();
		String rewardRate2=cbtConstant2.getString2();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("rewardRate1",rewardRate1+"%");
		jsonObject.put("rewardRate2",rewardRate2+"%");
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);	
	}
	

	/**
	 * 推荐奖励记录
	 */
	@PostMapping(value = "/getRewardRecord")
	@Authorization
	public ResponseEntity<ResultModel> getRewardRecord(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		
		double  allAchievement = 0.0;
		InvTree invTree = invTreeService.selectInvTreebyUserId(userId);
		if (invTree!=null) {
//			allAchievement = invTree.getTeamAssetInvest()+invTree.getAssetInvest();
			allAchievement = invTree.getTeamAssetInvest();
		}
			
			double directAchievement = this.cbtInvestService.selectAllInvestByuserId(userId);
//			List<CbtInvest> list = this.cbtInvestService.selectAllInvestListByuserId(userId);
//			
//			double directAchievement = list.stream().collect(Collectors.summingDouble(new ToDoubleFunction<CbtInvest>() {
//			    @Override
//			    public double applyAsDouble(CbtInvest cbtInvest) {
//			        double investAmount = cbtInvest.getInvestAmount();
//			        Integer ratio = cbtInvest.getRatio();
//			        return investAmount/ratio;
//			    }
//			}));
//		
			
//			List<User> users = userService.selectUsersListbyUserId(userId);
//			if (users.size()<1) {
//				directAchievement =0.0000; 
//			}else {
//				for(User user:users){
//					directAchievement +=cbtInvestService.selectTotalInvestByuserId(user.getUserId());
//				}	
//			}
			
			//用户存单总收益
//			double totalIncome=this.cbtIncomeService.selectTotalIncomeByuserId(userId);
			//用户总的签到奖励
//			double totalReward=this.cbtRewardService.selectTotalRewardByuserId(userId);
			//用户总的邀请奖励
//			double totalInvited=this.cbtInvitedIncomeService.getAllRewardByuserId(userId);
			
//			double totalInvited = cbtInvitedIncomeService.getAllIncomeByUserId(userId);
//			double directProfit =  this.cbtInvestService.selectAllInvestByuserId(userId)/Constants.AKB_INVEST_RATIO*0.1;
			double directProfit = this.cbtInvitedIncomeService.selectInvIncomeByuserId(userId);
			double selectDirectIncomeByuserId = cbtInvitedIncomeService.selectDirectIncomeByuserId(userId);
		
			double allProfit = directProfit+selectDirectIncomeByuserId;
			
//			double directProfit = this.cbtInvestService.selectAllInvestByuserId(userId)*0.1;
		
		
        //获取一级邀请列表
//        List<CbtReward> rewardList=this.cbtRewardService.getRewardRecordByuserId(page, rows, userId);
        List<User> rewardList = userService.selectUsersListbyUserId(userId);
		int totalPages=this.cbtRewardService.totalPages(userId, rows);
	
		JSONObject rewardObject = new JSONObject();
		if(rewardList == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			rewardObject.put("directAchievement", directAchievement);
			rewardObject.put("directProfit", directProfit);
//			rewardObject.put("allAchievement", allAchievement/Constants.AKB_INVEST_RATIO);
			rewardObject.put("allAchievement", allAchievement);
			rewardObject.put("allProfit", allProfit);
			rewardObject.put("rewardRecord", jsonArray);
			return new ResponseEntity<>(ResultModel.ok(rewardObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(User user : rewardList) {
			JSONObject jsonObject = new JSONObject();
			//被推荐人的ID
			int referee=user.getUserId();
			int count=this.cbtInvestService.countTotalInvestByuserId(referee);
			int investFlag=0;
			if(count > 0) {
				investFlag=1;
			}
			//被推荐人的注册账号
			String registerNo = user.getPhone();
			if (registerNo ==null) {
				registerNo = user.getMailNum();
			}
//			String registerNo=user.getPhone();
			registerNo=registerNo.replaceAll("(\\d{3})\\d{4}(\\d+)","$1****$2");
			//获取用户注册时间
//			User user=this.userService.selectByUserId(referee);
			Date createDate=user.getCreateDate();
			
			jsonObject.put("userId", referee);
			jsonObject.put("registerNo", registerNo);
			jsonObject.put("createDate", createDate);
			jsonObject.put("investFlag", investFlag);
			showList.add(jsonObject);
		}
		
		rewardObject.put("rewardRecord", showList);
		rewardObject.put("directAchievement", directAchievement);
		rewardObject.put("directProfit", directProfit);
		rewardObject.put("allAchievement", allAchievement);
		rewardObject.put("allProfit", allProfit);
		rewardObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(rewardObject), HttpStatus.OK);	
	}
	
	/**
	 * 投资记录
	 */
	@GetMapping(value = "/getInvestRecord")
	@Authorization
	public ResponseEntity<ResultModel> getInvestRecord(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		List<CbtCoininfo> investRecord=cbtCoinInfoService.getInvestRecordByuserId(page, rows, userId);
		JSONObject investObject = new JSONObject();
		int totalPages=this.cbtInvestService.totalPages(userId, rows);
		if(investRecord==null || page>totalPages) {
			JSONArray jsonArray = new JSONArray();
			investObject.put("investRecord", jsonArray);
			return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(CbtCoininfo coin:investRecord) {
			JSONObject jsonObject = new JSONObject();
			CbtInvest cbtInvest=coin.getCbtInvest();
			Date investDate=cbtInvest.getInvestDate();
			Double amount=cbtInvest.getInvestAmount();
			if(amount==null) {
				amount=0.0;
			}
			
			String coinSymbol=coin.getCoinSymbol();
			jsonObject.put("investDate", investDate);
			jsonObject.put("investAmount", amount);
			jsonObject.put("coinSymbol", coinSymbol);
			showList.add(jsonObject);
		}
		
		
		investObject.put("investRecord", showList);
		investObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);	
	}
	
	
	/**
	 * 充值记录
	 */
	
	@GetMapping(value = "/getRechargeRecord")
	@Authorization
	public ResponseEntity<ResultModel> getRechargeRecord(@RequestParam("userId") Integer userId,
			@RequestParam("coinId") Integer coinId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		System.out.println("coinId=>"+coinId);
		List<CbtCoininfo>rechargeRecord=cbtCoinInfoService.getRechargeRecordByuserId(page, rows, userId,coinId);
		JSONObject newObject = new JSONObject();
		int totalPages=this.cbtRechargeService.totalPages(userId,coinId,rows);
		if(rechargeRecord==null ||page>totalPages) {
			JSONArray jsonArray = new JSONArray();
			newObject.put("rechargeRecord",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
		}
		System.out.println(rechargeRecord);
		List<JSONObject> showList=new ArrayList<>();
		for(CbtCoininfo coin:rechargeRecord) {
			JSONObject jsonObject = new JSONObject();
			CbtRecharge cbtRecharge=coin.getCbtRecharge();
			Date rechargeDate=cbtRecharge.getRechargeDate();
			Double amount=cbtRecharge.getAmount();
			if(amount==null) {
				amount=0.0;
			}
			
			String coinSymbol=coin.getCoinSymbol();
			jsonObject.put("rechargeDate", rechargeDate);
			jsonObject.put("amount", amount);
			jsonObject.put("coinSymbol", coinSymbol);
			showList.add(jsonObject);
		}
		
		
		newObject.put("rechargeRecord", showList);
		newObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	
	}
	
	
	/**
	 * 币种行情
	 * @return
	 */
	@GetMapping(value = "/getQuotations")
	@Authorization
	public ResponseEntity<ResultModel> getQuotations() {
		ResultModel jsonObject=CoinQuotations.getCoinInfo();
		System.out.println("jsonObject:"+jsonObject);
		return new ResponseEntity<>(jsonObject, HttpStatus.OK);
	}
	
	

	
	/**
	 * 管理员账户登录
	 */
	@PostMapping(value = "/admin/login")
	public ResponseEntity<ResultModel> login(@RequestParam("phone") String phone,
			@RequestParam("passWord") String passWord,@RequestParam("code") String code) {
		
		if(phone == null || passWord == null) {
			return new ResponseEntity<ResultModel>(ResultModel.error(ResultStatus.DATA_NOT_NULL), HttpStatus.OK);
		}
		
		Admin user = this.adminService.selectByPhone(phone);

		if (null == user || // 未注册
				!user.getPassWord().equals(passWord)) { // 密码错误
			// 提示用户名或者密码错误
			return new ResponseEntity<>(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR), HttpStatus.OK);
		}
		//验证短信验证码
		if(code == null || code.equals("")) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.CODE_EMPTY), HttpStatus.OK);
		}
		String sendCode=map.get(phone);
		  System.out.println("sendCode:"+sendCode);
		  if(sendCode == null || sendCode.trim().isEmpty() || !sendCode.equals(code)){
		
			return new ResponseEntity<>(ResultModel.error(ResultStatus.CODE_ERROR), HttpStatus.OK);
		}
		// 生成token，保存用户登录状态
		TokenModel model = this.tokenManager.createToken(user.getUserId());
		//去除敏感信息
        user.setPassWord("");
		String UserJson = JSON.toJSONString(user);
		JSONObject userObject = JSON.parseObject(UserJson);
		userObject.put("token", model.getToken());
		map.remove(phone);
		return new ResponseEntity<>(ResultModel.ok(userObject), HttpStatus.OK);
	}
	
	/**
	 * 核实用户身份证 
	 * 
	 */
	@PostMapping(value = "/admin/verificationIDcard")
	@Authorization
	public ResponseEntity<ResultModel> verificationIDcard(
			 @RequestParam("page") Integer page,@RequestParam("rows") Integer rows,
			 @RequestParam(value = "flag", required = false) Integer flag1,
			 @RequestParam(value = "phone", required = false) String phone1,
			 @RequestParam(value = "userId", required = false) Integer userId1) {
		System.out.println("phone=>"+phone1);
		System.out.println("userId=>"+userId1);
		System.out.println("flag=>"+flag1);
		List<User>list=this.userService.getUserIDCard(flag1,page,rows,phone1,userId1);
		int totalPage=this.userService.totalPages(flag1, rows,phone1,userId1);
		JSONObject newObject = new JSONObject();
		if(list == null || page > totalPage) {
			JSONArray jsonArray = new JSONArray();
			newObject.put("totalPage", 0);
			newObject.put("userList",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(User user:list) {
			JSONObject jsonObject = new JSONObject();
			int userId=user.getUserId();
			String phone=user.getPhone();
			Date createDate=user.getCreateDate();
			String IDcardurlA=user.getIdcardUrla();
			String IDcardurlB=user.getIdcardUrlb();
			int flag=user.getFlag();
			
			jsonObject.put("userId", userId);
			jsonObject.put("phone", phone);
			jsonObject.put("flag", flag);
			jsonObject.put("createDate", createDate);
			jsonObject.put("IDcardurlA", IDcardurlA);
			jsonObject.put("IDcardurlB", IDcardurlB);
			showList.add(jsonObject);
		}
		newObject.put("userList",showList);
		newObject.put("totalPage", totalPage);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
	}
	
	/**
	 * 身份证核查状态
	 */
	@PostMapping(value = "/admin/verificationFlag")
	public ResponseEntity<ResultModel> verificationFlag(@RequestParam("userId") Integer userId,
			@RequestParam("userName") String userName,@RequestParam("flag") Integer flag) {
		System.out.println("userId=>"+userId);
		System.out.println("flag=>"+flag);
		User user=this.userService.selectByUserId(userId);
		user.setFlag(flag);
		user.setUserName(userName);
		this.userService.updateUser(userId, user);
		return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
	}
	
	/**
	 * 编辑文档
	 */
	@PostMapping(value = "/admin/createNews")
	public ResponseEntity<ResultModel> createNews(@RequestParam("title") String title,
			@RequestParam("content") String content,@RequestParam("languageFlag") Integer languageFlag) {
		CbtNews cbtNews=new CbtNews();
		cbtNews.setTitle(title);
		cbtNews.setContent(content);
		cbtNews.setLanguageFlag(languageFlag);
		cbtNews.setCreateDate(new Date());
		this.cbtNewsService.save(cbtNews);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);
	}
	
	
	/**
	 * 投资详情
	 */
	@PostMapping(value = "/getInvestDetails")
	@Authorization
	public ResponseEntity<ResultModel> getInvestDetails(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		List<CbtInvest> investList=this.cbtInvestService.selectInvestsByuserId(page, rows, userId);
		JSONObject investObject = new JSONObject();
		int total=investList.size();
		System.out.println("total=>"+total);
		
		int totalPages=this.cbtInvestService.realTotalPages(userId, rows);
		System.out.println("totalPages=>"+totalPages);
		
		if(investList == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			investObject.put("investList", jsonArray);
			return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		CbtCoininfo PCCoininfo = cbtCoinInfoService.selectCoinInfoBycoinSymbol("DFC");
		String coinSymbol = PCCoininfo.getCoinSymbol();
		String coinPic = PCCoininfo.getCoinUrl();
		for(CbtInvest cbtInvest : investList) {
			JSONObject jsonObject = new JSONObject();
			int investDuration=cbtInvest.getInvestDuration();
			Double amount=cbtInvest.getInvestAmount()/cbtInvest.getRatio();
			if(amount==null) {
				amount=0.0;
			}
//			CbtCoininfo coin=cbtInvest.getCbtCoininfo();
//			String coinPic=coin.getCoinUrl();
//			String coinSymbol=coin.getCoinSymbol();
			
			jsonObject.put("coinPic", coinPic);
			jsonObject.put("coinSymbol", coinSymbol);
			jsonObject.put("investAmount", amount);
			jsonObject.put("investDuration", investDuration);
			showList.add(jsonObject);
		}
		
		investObject.put("investList", showList);
		investObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(investObject), HttpStatus.OK);	
	}
	
	
	/**
	 * 邀请详情
	 */
	@PostMapping(value = "/getInvitedDetails")
	@Authorization
	public ResponseEntity<ResultModel> getInvitedDetails(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		//奖励日志表
		List<CbtReward> rewardList=this.cbtRewardService.getRewardRecordByuserId(page, rows, userId);
		int totalPages=this.cbtRewardService.totalPages(userId, rows);
		JSONObject rewardObject = new JSONObject();
		if(rewardList == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			rewardObject.put("invitedList", jsonArray);
			return new ResponseEntity<>(ResultModel.ok(rewardObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		rewardList.stream().forEach(reward->{
			
			JSONObject jsonObject = new JSONObject();
			//被推荐人的ID
			int referee=reward.getReferee();
			int count=this.cbtInvestService.countTotalInvestByuserId(referee);
			int investFlag=0;
			if(count > 0) {
				investFlag=1;
			}
			//被推荐人的注册账号
			String registerNo=reward.getRegisterNo();
			registerNo=registerNo.replaceAll("(\\d{3})\\d{4}(\\d+)","$1****$2");
			//获取用户注册时间
			User user=this.userService.selectByUserId(referee);
			Date createDate=user.getCreateDate();
			
			jsonObject.put("registerNo", registerNo);
			jsonObject.put("createDate", createDate);
			jsonObject.put("userId", reward.getReferee());
			jsonObject.put("investFlag", investFlag);
			showList.add(jsonObject);
		});
		rewardObject.put("invitedList", showList);
		rewardObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(rewardObject), HttpStatus.OK);	
	}
	
	/**
	 * 邀请收益
	 */
	@PostMapping(value = "/getInvitedIncome")
	@Authorization
	public ResponseEntity<ResultModel> getInvitedIncome(@RequestParam("userId") Integer userId,
			@RequestParam("page") Integer page,
			@RequestParam("row") Integer rows) {
		List<CbtInvitedIncome> invitedList=this.cbtInvitedIncomeService.selectAllByuserId(page, rows, userId);
		int totalPages=this.cbtInvitedIncomeService.totalPages(rows, userId);
		JSONObject invitedObject = new JSONObject();
		if(invitedList == null || page > totalPages) {
			JSONArray jsonArray = new JSONArray();
			invitedObject.put("invitedList", jsonArray);
			return new ResponseEntity<>(ResultModel.ok(invitedObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(CbtInvitedIncome cbtInvitedIncome : invitedList) {
			JSONObject jsonObject = new JSONObject();
			//被推荐人的ID
			int referee=cbtInvitedIncome.getRegisterNo();
			//被推荐人的注册账号
			CbtReward cbtReward=this.cbtRewardService.selectRewardByrefereeId(referee);
			String registerNo=cbtReward.getRegisterNo();
			registerNo=registerNo.replaceAll("(\\d{3})\\d{4}(\\d+)","$1****$2");
			//获取返利时间
			Date createDate=cbtInvitedIncome.getCreateDate();
			//奖励数量
			double amount1=cbtInvitedIncome.getAmount();
			BigDecimal decimal = new BigDecimal(Double.toString(amount1));
	        BigDecimal amount = decimal.setScale(2,BigDecimal.ROUND_DOWN);
	        
			jsonObject.put("registerNo", registerNo);
			jsonObject.put("createDate", createDate);
			jsonObject.put("amount", amount);
			showList.add(jsonObject);
		}
		invitedObject.put("invitedList", showList);
		invitedObject.put("totalPage", totalPages);
		return new ResponseEntity<>(ResultModel.ok(invitedObject), HttpStatus.OK);	
	}
	
	
	
	//WalletAccount walletAccount = walletProcess.DoRedemptionETH(walleatAdress, ethWithdrawCnt);
			//System.out.println("walletAccount.getResult():"+walletAccount.getResult());
			
//			if (walletAccount.getResult()) {
//				String hash = walletAccount.getHash();	
//				//先进行查找hash是否存在，如果存在则进行调过
//				if (this.cbtDrawService.isHashExist(hash)) {
//					return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"cbtWithdrawRepeat"),HttpStatus.OK);
//				}
//			
//				//给用户提现表插入数据
//				CbtDraw cbtDraw=new CbtDraw();
//				cbtDraw.setAccount(walleatAdress);
//				cbtDraw.setAmount(value);
//				cbtDraw.setDrawHash(hash);
//				cbtDraw.setEthPrice(ethPrice);
//				cbtDraw.setFee(fee);
//				cbtDraw.setDrawDate(new Date());
//				cbtDraw.setUserId(userId);
//				//提现状态: 0 代表提现失败;1 代表提现成功;2 代表提现中...;
//				cbtDraw.setStatus(2);
//				this.cbtDrawService.save(cbtDraw);
//				
//				
//				int drawId=this.cbtDrawService.selectMaxDrawId();
//				CbtPayLog cbtPayLog=new CbtPayLog();
//				cbtPayLog.setCbtAmount(value);
//				cbtPayLog.setDrawDate(new Date());
//				cbtPayLog.setDrawHash(hash);
//				cbtPayLog.setDrawId(drawId);
//				cbtPayLog.setEthAmount(ethWithdrawCnt);
//				cbtPayLog.setEthPrice(ethPrice);
//				cbtPayLog.setFee(fee);
//				cbtPayLog.setUserId(userId);
//				cbtPayLog.setWalletAddress(walleatAdress);
//				cbtPayLog.setFlag(2);
//				this.cbtPayLogService.save(cbtPayLog);
	/**
	 * 用户转账
	 */
	@DuplicateSubmitToken
	@PostMapping(value = "/doChange")
	@Authorization
	public ResponseEntity<ResultModel> doChangeAutio(@RequestParam("userId") Integer userId,
			@RequestParam("coinId") Integer coinId,
			@RequestParam("address") String address,
			@RequestParam("value") Double value,
			@RequestParam("remark") String remark,
			@RequestParam("feeRatio") Double feeRatio) {
		synchronized (userId) {
			System.out.println("feeRatio====="+feeRatio);
			//语言切换基类
			ResourceBundle myResourcesBundle =International.getLanguage(request);
			//币种简称
            CbtCoininfo cbtCoininfo = this.cbtCoinInfoService.selectCoinInfoBycoinId(coinId);
            String coinSymbol = cbtCoininfo.getCoinSymbol();
			//获取用户当前币种数量
            Double amount = 0.0;
           if(coinSymbol.equals("DFC")){
            	 double totalIncome = this.cbtIncomeService.selectTotalIncomeByuserId(userId);
                 //用户总的邀请奖励
                 double totalInvited = this.cbtInvitedIncomeService.selectInvIncomeByuserId(userId);
                 //用户极差奖励
                 double selectDirectIncomeByuserId = cbtInvitedIncomeService.selectDirectIncomeByuserId(userId);
                 //用户PC金额
                 double rechargeAmount = cbtRechargeService.getRechargeAmount(userId,coinId );
                 amount = totalIncome + rechargeAmount + selectDirectIncomeByuserId + totalInvited;
            }else {
           	 amount = this.cbtRechargeService.getRechargeAmount(userId, coinId);
           }
			
			User selectByUserId = userService.selectByUserId(userId);
			if (selectByUserId.getStatus()==2) {
				 //钱包地址检查错误
				   return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"wrongWalletAddress"), HttpStatus.OK);
			}
			
			String regex = null;
            if (cbtCoininfo.getCoinSymbol().equals("AKB")) {
                regex = "^[A-Za-z0-9]{43}$";
            } else {
                regex = "^[A-Za-z0-9]{42}$";
            }
			  
			  if (!address.matches(regex)) {
			   //钱包地址检查错误
			   return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"wrongWalletAddress"), HttpStatus.OK);
			  }
			
			if (value<=0) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"zeroValue"), HttpStatus.OK);
			}
			
			Double selectMinBycoinId = cbtMinerRateService.selectMinBycoinId(coinId);
			Double selectMaxBycoinId = cbtMinerRateService.selectMaxBycoinId(coinId);
			if (feeRatio<selectMinBycoinId || feeRatio>selectMaxBycoinId) {
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"feeRatioIsError"), HttpStatus.OK);
			}
			
			if( value <= feeRatio){
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"valueNotEnough"), HttpStatus.OK);
			}
		
			if(value > amount ){
				return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"capitalNotEnough"), HttpStatus.OK);
			}
			//转账手续费
			double fee= 0.0;
			if(cbtCoininfo.getCoinSymbol().equals("DFC")){
				fee = value*selectMinBycoinId*0.01;
			}else{
				 fee = feeRatio;
			}
			
			//用户得到的数量
//			double getAmount=value-fee;
			 BigDecimal p1 = new BigDecimal(Double.toString(value));
		        BigDecimal p2 = new BigDecimal(Double.toString(fee));
		        double getAmount =  p1.subtract(p2).setScale(4, BigDecimal.ROUND_DOWN).doubleValue();
			
			
			CbtConstant cbtConstant=this.cbtConstantService.selectConstantById(4);
			
				int countTodayByUserId = cbtAutoExchangeService.countTodayByUserId(userId);
				if (countTodayByUserId< cbtConstant.getNum2().intValue() && value<=cbtConstant.getNum1()) {
					WalletProcess walletProcess = new WalletProcess();
					WalletAccount walletAccount = null;
	                if (cbtCoininfo.getCoinSymbol().equals("AKB")) {
	                    walletAccount = walletProcess.DoRedemptionETH(address, getAmount);
	                } else if(cbtCoininfo.getCoinSymbol().equals("DFC")) {
	                    walletAccount = walletProcess.DoRedemptionDFC(address, getAmount);
	                }else if (cbtCoininfo.getCoinSymbol().equals("USDT")){
	                	walletAccount = walletProcess.DoUSDTRedemptionETH(address, getAmount);
	                }
					
					if (walletAccount.getResult()) {
						String hash = walletAccount.getHash();	
						//先进行查找hash是否存在，如果存在则进行调过
						if (this.cbtAutoExchangeService.isHashExist(hash)) {
							return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"cbtWithdrawRepeat"),HttpStatus.OK);
						}
					//给用户提现表插入数据
						CbtAutoExchange cbtAutoExchange  = new CbtAutoExchange();
//					CbtDraw cbtDraw=new CbtDraw();
					cbtAutoExchange.setAccount(address);
					cbtAutoExchange.setAmount(value);
					cbtAutoExchange.setDrawHash(hash);
					cbtAutoExchange.setEthPrice(cbtCoininfo.getCoinPriceRmb());
					cbtAutoExchange.setFee(fee);
					cbtAutoExchange.setDrawDate(new Date());
					cbtAutoExchange.setUserId(userId);
					cbtAutoExchange.setCoinId(coinId);
					//提现状态: 0 代表提现失败;1 代表提现成功;2 代表提现中...;
					cbtAutoExchange.setStatus(2);
					this.cbtAutoExchangeService.save(cbtAutoExchange);
					
					CbtRecharge cbtRecharge=new CbtRecharge();
					cbtRecharge.setCoinId(coinId);
					cbtRecharge.setUserId(userId);
					//用户币减少
					cbtRecharge.setAmount(-value);
					cbtRecharge.setRechargeDate(new Date());
					cbtRecharge.setBlockNum(0);
					this.cbtRechargeService.save(cbtRecharge);
					
					
					int drawId=this.cbtAutoExchangeService.selectMaxDrawId();
					CbtPayLog cbtPayLog=new CbtPayLog();
					cbtPayLog.setCbtAmount(value);
					cbtPayLog.setDrawDate(new Date());
					cbtPayLog.setDrawHash(hash);
					cbtPayLog.setDrawId(drawId);
					cbtPayLog.setEthAmount(value);
					cbtPayLog.setEthPrice(cbtCoininfo.getCoinPriceRmb());
					cbtPayLog.setFee(fee);
					cbtPayLog.setUserId(userId);
					cbtPayLog.setWalletAddress(address);
					cbtPayLog.setFlag(2);
					this.cbtPayLogService.save(cbtPayLog);
				}
				}
				if (countTodayByUserId>=cbtConstant.getNum2().intValue() || value>cbtConstant.getNum1()) {
					CbtChange cbtChange = new CbtChange();
					cbtChange.setAddress(address);
					cbtChange.setAmount(value);
					cbtChange.setCoinId(coinId);
					cbtChange.setCoinSymbol(coinSymbol);
					cbtChange.setUserId(userId);
					cbtChange.setFeeRatio(feeRatio);
					cbtChange.setFee(fee);
					cbtChange.setRemark(remark);
					cbtChange.setGetAmount(getAmount);
					
					this.cbtChangeService.save(cbtChange);
					
					//更新用户充值表
					CbtRecharge cbtRecharge=new CbtRecharge();
					cbtRecharge.setCoinId(coinId);
					cbtRecharge.setUserId(userId);
					//用户币减少
					cbtRecharge.setAmount(-value);
					cbtRecharge.setRechargeDate(new Date());
					cbtRecharge.setBlockNum(0);
					this.cbtRechargeService.save(cbtRecharge);
					
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("result", true);
					
					try {
						SendPhoneMessage.sendMsg("13738113541","需要转账的用户ID"+userId);
					} catch (HttpException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				
			}
			
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("result", true);
			return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);	
		}
	
	}
	
	
//	/**
//	 * 用户转账记录
//	 */
//	@PostMapping(value = "/getChangeRecord")
//	@Authorization
//	public ResponseEntity<ResultModel> getChangeRecord(@RequestParam("userId") Integer userId,
//			@RequestParam("coinId") Integer coinId,
//			@RequestParam("page") Integer page,
//			@RequestParam("row") Integer rows) {
////		List<CbtChange> changeList=this.cbtChangeService.getChangeRecord(userId, coinId,page,rows);
//		List<CbtChangeDraw> changeList = cbtChangeDrawService.getChangeRecord(userId, page, rows);
//		int totalPages=this.cbtChangeDrawService.totalPages(userId, rows);
//		JSONObject changeObject = new JSONObject();
//		if(changeList == null || page > totalPages) {
//			JSONArray jsonArray = new JSONArray();
//			changeObject.put("changeRecord", jsonArray);
//			return new ResponseEntity<>(ResultModel.ok(changeObject), HttpStatus.OK);
//		}
//		List<JSONObject> showList=new ArrayList<>();
//		for(CbtChangeDraw cbtChangeDraw : changeList) {
//			JSONObject jsonObject = new JSONObject();
//			//转账地址
//			String address=cbtChangeDraw.getAddress();
//			//转账时间
//			Date createDate=cbtChangeDraw.getCreateDate();
//			//转账数量
//			double amount1=cbtChangeDraw.getAmount();
//			BigDecimal decimal = new BigDecimal(Double.toString(amount1));
//	        BigDecimal amount = decimal.setScale(4,BigDecimal.ROUND_DOWN);
//			//转账状态
//	        int status=cbtChangeDraw.getStatus();
//	        
//			jsonObject.put("address", address);
//			jsonObject.put("createDate", createDate);
//			jsonObject.put("amount", amount);
//			jsonObject.put("status", status);
//			showList.add(jsonObject);
//		}
//		List<CbtDraw> selectAllDrawByuserId = cbtDrawService.selectAllDrawByuserId(userId);
//		
//		changeObject.put("changeRecord", showList);
//		changeObject.put("totalPage", totalPages);
//		return new ResponseEntity<>(ResultModel.ok(changeObject), HttpStatus.OK);	
//	}
	
	 /**
     * 用户转账记录
     */
   
    @PostMapping(value = "/getChangeRecord")
    @Authorization
    public ResponseEntity<ResultModel> getChangeRecord(@RequestParam("userId") Integer userId,
                                                       @RequestParam("coinId") Integer coinId,
                                                       @RequestParam("page") Integer page,
                                                       @RequestParam("row") Integer rows) {

        List<CbtChangeDraw> changeList = cbtChangeDrawService.getChangeRecord(userId, coinId, page, rows);
        int totalPages = this.cbtChangeDrawService.totalPages(userId, rows);
        JSONObject changeObject = new JSONObject();
        if (changeList == null || page > totalPages) {
            JSONArray jsonArray = new JSONArray();
            changeObject.put("changeRecord", jsonArray);
            return new ResponseEntity<>(ResultModel.ok(changeObject), HttpStatus.OK);
        }
        List<JSONObject> showList = new ArrayList<>();
        for (CbtChangeDraw cbtChangeDraw : changeList) {
            JSONObject jsonObject = new JSONObject();
            //转账地址
            String address = cbtChangeDraw.getAddress();
            //转账时间
            Date createDate = cbtChangeDraw.getCreateDate();
            //转账数量
            double amount1 = cbtChangeDraw.getAmount();
            BigDecimal decimal = new BigDecimal(Double.toString(amount1));
            BigDecimal amount = decimal.setScale(4, BigDecimal.ROUND_DOWN);
            //转账状态
            int status = cbtChangeDraw.getStatus();

            jsonObject.put("address", address);
            jsonObject.put("createDate", createDate);
            jsonObject.put("amount", amount);
            jsonObject.put("status", status);
            showList.add(jsonObject);
        }
        changeObject.put("changeRecord", showList);
        changeObject.put("totalPage", totalPages);
        return new ResponseEntity<>(ResultModel.ok(changeObject), HttpStatus.OK);
    }
	
	/**
	 * 校验用户支付密码
	 */
	@PostMapping(value = "/checkPayPassWord")
	@Authorization
	public ResponseEntity<ResultModel> checkPayPassWord(@RequestParam("userId") Integer userId,
			@RequestParam("payPassWord") String payPassWord) {
		//语言切换基类
		ResourceBundle myResourcesBundle =International.getLanguage(request);
		User user=this.userService.selectByUserId(userId);
		//用户支付密码
		String payWord=user.getPayPassword();
		
		if(payWord == null || payWord.equals("")) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"payPasswordEmpty"), HttpStatus.OK);
		}
		if( !payWord.equals(payPassWord)) {
			return new ResponseEntity<>(ResultModel.error(myResourcesBundle,"payWordError"), HttpStatus.OK);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);	
	}
	
	/**
	 * 获取矿工费率
	 */
	@PostMapping(value = "/getMinerRate")
	@Authorization
	public ResponseEntity<ResultModel> getMinerRate(@RequestParam("coinId") Integer coinId) {
		List<CbtMinerRate> list=this.cbtMinerRateService.selectBycoinId(coinId);
		return new ResponseEntity<>(ResultModel.ok(list), HttpStatus.OK);	
	}
	
	
	/**
	 * 查看用户转账记录
	 */
	@PostMapping(value = "/admin/verificationChange")
	
	public ResponseEntity<ResultModel> verificationChange(
			 @RequestParam("page") Integer page,@RequestParam("rows") Integer rows,
			 @RequestParam(value = "status", required = false) Integer status,
			 @RequestParam(value = "phone", required = false) String phone,
			 @RequestParam(value = "userId", required = false) Integer userId,
			 @RequestParam(value = "coinSymbol", required = false) String coinSymbol) {
		System.out.println("phone=>"+phone);
		System.out.println("userId=>"+userId);
		System.out.println("status=>"+status);
		
		if(phone != null &&  !phone.equals("")) {
			User user=this.userService.selectByPhone(phone);
			if(user == null) {
				return new ResponseEntity<>(ResultModel.error(ResultStatus.USER_NOT_FOUND), HttpStatus.OK);
			}
			userId=user.getUserId();
		 }
		
		List<CbtChange>list=this.cbtChangeService.getChangeList(status, userId, coinSymbol, page, rows);
		int totalPage=this.cbtChangeService.getTotalPages(status, userId, coinSymbol, rows);
		JSONObject newObject = new JSONObject();
		if(list == null || page > totalPage) {
			JSONArray jsonArray = new JSONArray();
			newObject.put("totalPage", 0);
			newObject.put("changeList",jsonArray);
			return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
		}
		List<JSONObject> showList=new ArrayList<>();
		for(CbtChange cbtChange : list) {
			JSONObject jsonObject = new JSONObject();
			//转账ID
			int Id=cbtChange.getId();
			//用户ID
			int userId1=cbtChange.getUserId();
			User user=this.userService.selectByUserId(userId1);
			String phone1=user.getPhone();
			//币种简称
			String coinSymbol1=cbtChange.getCoinSymbol();
			//提现地址
			String address=cbtChange.getAddress();
			//得到的数量
			double amount=cbtChange.getGetAmount();
			//状态
			int status1=cbtChange.getStatus();
			//备注
			String remark=cbtChange.getRemark();
			
			Date createDate=cbtChange.getCreateDate();
			
			jsonObject.put("Id", Id);
			jsonObject.put("userId", userId1);
			jsonObject.put("phone", phone1);
			jsonObject.put("coinSymbol", coinSymbol1);
			jsonObject.put("address", address);
			jsonObject.put("amount", amount);
			jsonObject.put("status", status1);
			jsonObject.put("remark", remark);
			jsonObject.put("createDate", createDate);
			
			showList.add(jsonObject);
		}
		newObject.put("changeList",showList);
		newObject.put("totalPage", totalPage);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
	}
	
	/**
	 * 审核转账状态
	 */
	@PostMapping(value = "/admin/changeStatus")
	public ResponseEntity<ResultModel> changeStatus(@RequestParam("Id") Integer Id,
			@RequestParam("status") Integer status) {
		System.out.println("Id=>"+Id);
		System.out.println("status=>"+status);
		CbtChange cbtChange=this.cbtChangeService.selectById(Id);
		cbtChange.setStatus(status);
		this.cbtChangeService.updateChange(Id, cbtChange);
		return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
	}
	
	 /**
     * 用户列表
     */
   
    @PostMapping(value = "/admin/invUserTree")
    @Authorization
    public ResponseEntity<ResultModel> verificationChange(
            @RequestParam("page") Integer page, @RequestParam("rows") Integer rows,
            @RequestParam(value = "phone", required = false) String phone) {
        System.out.println("phone=>" + phone);
        
        if (phone != null && !phone.equals("")) {
            User user = userService.selectByPhone(phone);
            if (user == null) {
                return new ResponseEntity<>(ResultModel.error(ResultStatus.USER_NOT_FOUND), HttpStatus.OK);
            }
            List<JSONObject> collect1 = new ArrayList<>();
            InvTree invTree = invTreeService.selectInvTreebyUserId(user.getUserId());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", invTree.getUserId());
            jsonObject.put("phone", user.getPhone());
            User selectByUserId = userService.selectByUserId(user.getReferer());
            if(selectByUserId!=null){
            	jsonObject.put("referer", selectByUserId.getPhone());
            	}else{
            		jsonObject.put("referer", "DFC");
            	}
            if(invTree!=null){
            	 jsonObject.put("teamInv", invTree.getTeamAssetInvest());
                 jsonObject.put("userInv", invTree.getAssetInvest());
                 jsonObject.put("userStar", invTree.getUserStar());
               
            }else{
            	 jsonObject.put("teamInv", 0.0);
                 jsonObject.put("userInv", 0.0);
                 CbtUserStar selectAllByUserId = cbtUserStarService.selectAllByUserId(user.getUserId());
                 if(selectAllByUserId!=null){
                	 jsonObject.put("userStar", selectAllByUserId.getAccount());
                 }else{
                	 jsonObject.put("userStar", 0);
                 }
            }
           
            collect1.add(jsonObject);
            JSONObject newObject = new JSONObject();
            newObject.put("changeList", collect1);
            newObject.put("totalPage", 1);
            return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
        }
        User user = new User();
        List<User> allUsers = userService.getAllUsers(page, rows, user);
        List<JSONObject> collect = allUsers.stream().map(ss->{
        	 JSONObject jsonObject = new JSONObject();
        	 InvTree invtree = invTreeService.selectInvTreebyUserId(ss.getUserId());
        	 jsonObject.put("userId", ss.getUserId());
             jsonObject.put("phone", ss.getPhone());
             User selectByUserId = userService.selectByUserId(ss.getReferer());
             if(selectByUserId!=null){
             	jsonObject.put("referer", selectByUserId.getPhone());
             	}else{
             		jsonObject.put("referer", "DFC");
             	}
             if(invtree!=null){
            	 jsonObject.put("teamInv", invtree.getTeamAssetInvest());
                 jsonObject.put("userInv", invtree.getAssetInvest());
                 jsonObject.put("userStar", invtree.getUserStar());
            }else{
            	 jsonObject.put("teamInv", 0.0);
                 jsonObject.put("userInv", 0.0);
                 CbtUserStar selectAllByUserId = cbtUserStarService.selectAllByUserId(ss.getUserId());
                 if(selectAllByUserId!=null){
                	 jsonObject.put("userStar", selectAllByUserId.getAccount());
                 }else{
                	 jsonObject.put("userStar", 0);
                 }
                 
            }
            
           
        	return jsonObject;
        }).collect(Collectors.toList());

        int totalPage = userService.totalAllPages(rows);   
        JSONObject newObject = new JSONObject();
        newObject.put("changeList", collect);
        newObject.put("totalPage", totalPage);
        return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
    }
    
    
    @PostMapping(value = "/admin/updateUserStar")
	@Authorization
	public ResponseEntity<ResultModel> updateUserStar(@RequestParam("userId") Integer userId,
			@RequestParam("star") Integer star) {
    	
    	User selectByUserId = userService.selectByUserId(userId);
    	CbtUserStar selectAllByUserId = cbtUserStarService.selectAllByUserId(userId);
    	CbtUserStar userStar = new CbtUserStar();
		userStar.setUserId(userId);
		userStar.setAccount(star);
    	if(selectAllByUserId!=null){
    		cbtUserStarService.update(userId, userStar);
    	}else{
    		
    		cbtUserStarService.save(userStar);
    	}
    	InvTree invtree = invTreeService.selectInvTreebyUserId(userId);
    	if(invtree!=null){
    		invtree.setUserStar(star);
    		invtree.setTeamMaxStar(star);
    		invTreeService.updateInvTreebyUserId(invtree);
    		
    	}
    	
		return new ResponseEntity<>(ResultModel.ok(null), HttpStatus.OK);
		
	}
    
    @PostMapping(value = "/admin/drawMoneyList")
   	@Authorization
   	public ResponseEntity<ResultModel> drawMoneyList( @RequestParam("page") Integer page, @RequestParam("rows") Integer rows,
   			@RequestParam(value = "phone", required = false)String phone,@RequestParam(value = "coinId", required = false)Integer coinId,
   			@RequestParam(value = "startTime", required = false)String startTime,@RequestParam(value = "endTime", required = false)String endTime) throws ParseException {
    	Integer userId = null;
       	if(phone!=null && !phone.equals("")){
       		User selectByPhone = userService.selectByPhone(phone);
       		if(selectByPhone==null){
       			return new ResponseEntity<>(ResultModel.ok(null), HttpStatus.OK);
       		}
       		userId= selectByPhone.getUserId();
       	}
       	int totalPages=this.cbtRechargeService.ListTotal(userId,coinId, startTime, endTime, rows);
    	List<CbtRecharge> drawMoneyList = cbtRechargeService.drawMoneyList(page, rows,userId ,coinId, startTime, endTime);
    	List<JSONObject> collect=new ArrayList<>();
    	if(drawMoneyList!=null){
    	
    	collect = drawMoneyList.stream().map(s->{
    		JSONObject jsonObject = new JSONObject();
    		User selectByUserId = userService.selectByUserId(s.getUserId());
    		jsonObject.put("phone", selectByUserId.getPhone());
    		CbtCoininfo selectCoinInfoBycoinId = cbtCoinInfoService.selectCoinInfoBycoinId(s.getCoinId());
    		jsonObject.put("coininfo", selectCoinInfoBycoinId.getCoinSymbol());
    		jsonObject.put("amount", s.getAmount());
    		jsonObject.put("time", s.getRechargeDate());
    		return jsonObject;
    	}).collect(Collectors.toList());
    	}
    	JSONObject newObject = new JSONObject();
    	newObject.put("list", collect);
		newObject.put("totalPage", totalPages);
       	
   		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
   	}
    
    @PostMapping(value = "/admin/changeMoneyList")
   	@Authorization
   	public ResponseEntity<ResultModel> changeMoneyList( @RequestParam("page") Integer page, @RequestParam("rows") Integer rows,
   			@RequestParam(value = "phone", required = false)String phone,@RequestParam(value = "coinId", required = false)Integer coinId,
   			@RequestParam(value = "startTime", required = false)String startTime,@RequestParam(value = "endTime", required = false)String endTime) throws ParseException {
    	Integer userId = null;
       	if(phone!=null && !phone.equals("")){
       		User selectByPhone = userService.selectByPhone(phone);
       		if(selectByPhone==null){
       			return new ResponseEntity<>(ResultModel.ok(null), HttpStatus.OK);
       		}
       		userId= selectByPhone.getUserId();
       	}
       	int totalPages=this.cbtChangeDrawService.ListTotal(userId,coinId, startTime, endTime, rows);
    	List<CbtChangeDraw> drawMoneyList = cbtChangeDrawService.changeMoneyList(page, rows,userId ,coinId, startTime, endTime);
    	List<JSONObject> collect=new ArrayList<>();
    	if(drawMoneyList!=null){
    	 collect = drawMoneyList.stream().map(s->{
    		JSONObject jsonObject = new JSONObject();
    		User selectByUserId = userService.selectByUserId(s.getUserId());
    		jsonObject.put("phone", selectByUserId.getPhone());
    		CbtCoininfo selectCoinInfoBycoinId = cbtCoinInfoService.selectCoinInfoBycoinId(s.getCoinId());
    		jsonObject.put("coininfo", selectCoinInfoBycoinId.getCoinSymbol());
    		jsonObject.put("amount", s.getAmount());
    		jsonObject.put("time", s.getCreateDate());
    		return jsonObject;
    	}).collect(Collectors.toList());
    	}
    	
    	JSONObject newObject = new JSONObject();
    	newObject.put("list", collect);
		newObject.put("totalPage", totalPages);
       	
   		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
   	}
    
    
    @PostMapping(value = "/admin/investMoneyList")
   	@Authorization
   	public ResponseEntity<ResultModel> investMoneyList( @RequestParam("page") Integer page, @RequestParam("rows") Integer rows,
   			@RequestParam(value = "phone", required = false)String phone,@RequestParam(value = "coinId", required = false)Integer coinId,
   			@RequestParam(value = "startTime", required = false)String startTime,@RequestParam(value = "endTime", required = false)String endTime) throws ParseException {
    	Integer userId = null;
       	if(phone!=null && !phone.equals("")){
       		User selectByPhone = userService.selectByPhone(phone);
       		if(selectByPhone==null){
       			return new ResponseEntity<>(ResultModel.ok(null), HttpStatus.OK);
       		}
       		userId= selectByPhone.getUserId();
       	}
       	int totalPages=this.cbtInvestService.ListTotal(userId,coinId, startTime, endTime, rows);
    	List<CbtInvest> drawMoneyList = cbtInvestService.investMoneyList(page, rows,userId ,coinId, startTime, endTime);
    	List<JSONObject> collect=new ArrayList<>();
    	if(drawMoneyList!=null){
    	 collect = drawMoneyList.stream().map(s->{
    		JSONObject jsonObject = new JSONObject();
    		User selectByUserId = userService.selectByUserId(s.getUserId());
    		jsonObject.put("phone", selectByUserId.getPhone());
    		CbtCoininfo selectCoinInfoBycoinId = cbtCoinInfoService.selectCoinInfoBycoinId(s.getCoinId());
    		jsonObject.put("coininfo", selectCoinInfoBycoinId.getCoinSymbol());
    		jsonObject.put("investAmount", s.getInvestAmount());
    		jsonObject.put("time", s.getInvestDate());
    		jsonObject.put("ratio", s.getRatio());
    		jsonObject.put("ethPrice", s.getEthPrice());
    		jsonObject.put("price", s.getPrice());
    		jsonObject.put("dfcPrice", s.getDfcPrice());		
    		return jsonObject;
    	}).collect(Collectors.toList());
    	}
    	
    	JSONObject newObject = new JSONObject();
    	newObject.put("list", collect);
		newObject.put("totalPage", totalPages);
       	
   		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
   	}
    
    @PostMapping(value = "/admin/walletInfo")
   	@Authorization
   	public ResponseEntity<ResultModel> walletInfo( ) throws ParseException {
    	WalletProcess walletProcess = new WalletProcess();
    	Object walletInfo = walletProcess.WalletInfo();
       	
   		return new ResponseEntity<>(ResultModel.ok(walletInfo), HttpStatus.OK);
   	}
    
    @PostMapping(value = "/admin/teamList")
   	@Authorization
   	public ResponseEntity<ResultModel> investMoneyList(@RequestParam(value = "coinId", required = false)Integer coinId, 
   			@RequestParam(value = "startTime", required = false)String startTime,@RequestParam(value = "endTime", required = false)String endTime) throws ParseException {
    	
    	double allInvest = cbtInvestService.allInvest(coinId,startTime,endTime);
    	double allDraw = cbtRechargeService.allDraw(coinId, startTime, endTime);
    	double allChange = cbtChangeDrawService.allChange(coinId, startTime, endTime);
    	
    	JSONObject newObject = new JSONObject();
    	newObject.put("allInvest", allInvest);
		newObject.put("allDraw", allDraw);
		newObject.put("allChange", allChange);
       	
   		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);
   	}
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

	

	@PostMapping(value = "/setAsset")
	@Authorization
	public ResponseEntity<ResultModel> setAsset(@RequestParam("userId") Integer userId,
			@RequestParam("asset") String asset, @RequestParam("coinId") Integer coinId) {
		
		if (true) {
			CbtAsset cbtAssets  = cbtAssetService.selectAssetByuserId(userId);
			CbtAsset cbtAsset = new CbtAsset();
			cbtAsset.setUserId(userId);
			cbtAsset.setAsset(Double.valueOf(asset));
			cbtAsset.setFreezeFlag(false);
			CbtRecharge cbtRecharge = new CbtRecharge();
			cbtRecharge.setUserId(userId);
			cbtRecharge.setAmount(Double.valueOf(asset));
			cbtRecharge.setCoinId(coinId);
			cbtRecharge.setRechargeDate(new Date());
			cbtRecharge.setBlockNum(0);
			
			
			if (cbtAssets==null) {
				cbtRechargeService.save(cbtRecharge);
				cbtAssetMapper.insert(cbtAsset);
			}else{
				cbtAssets.setAsset(Double.valueOf(asset));
				cbtRechargeService.save(cbtRecharge);
				cbtAssetService.updateAsset(userId, cbtAssets);
			}
	
//			cbtAssetService.save(cbtAsset);
			return new ResponseEntity<>(ResultModel.ok(cbtAsset), HttpStatus.OK);
		}else {
			return new ResponseEntity<>(ResultModel.ok(null), HttpStatus.OK);
		}
		
	}


	@PostMapping(value = "/changeTree")
	//@Authorization
	public ResponseEntity<ResultModel> changeTree(@RequestParam("userId") Integer userId, 
			@RequestParam("extractFlag") Integer extractFlag) {
		//语言切换基类
		List<CbtInvest> changeInv = cbtInvestService.getChangeInv(userId, extractFlag);
		changeInv.stream().forEach(inv->{
			//更新投资表状态为已投资计算状态
			cbtInvestService.updateFlag(inv.getId(), 0);

			User user2 = userService.selectByUserId(inv.getUserId());
			invitationTreeService.createOneNodeList(user2, 0, 1000);
		});

		JSONObject newObject = new JSONObject();
		newObject.put("asset",true);
		return new ResponseEntity<>(ResultModel.ok(newObject), HttpStatus.OK);	

	}

}